For my approach, I use a dictionary to store the sum of values for each unique id. I iterate through both nums1
and nums2
, adding their values to the dictionary. After processing both arrays, I convert the dictionary into a sorted list of lists.
class Solution:
def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:
merged_dict = {}
for id_, val in nums1:
merged_dict[id_] = merged_dict.get(id_, 0) + val
for id_, val in nums2:
merged_dict[id_] = merged_dict.get(id_, 0) + val
result = sorted([[id_, val] for id_, val in merged_dict.items()])
return result
- Time: O(n + m) since each array is processed once
- Space: O(n + m) due to storing unique ids in the dictionary before sorting
