Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 2, 2025 21:34
Show Gist options
  • Save Ifihan/e3f3ececd55e8e7d0af9454911af423e to your computer and use it in GitHub Desktop.
Save Ifihan/e3f3ececd55e8e7d0af9454911af423e to your computer and use it in GitHub Desktop.
Merge Two 2D Arrays by Summing Values

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n + m) since each array is processed once
  • Space: O(n + m) due to storing unique ids in the dictionary before sorting
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment