Merge Two 2D Arrays by Summing Values (LeetCode 2570): Solution and Explanation

Easy
Array
Hash Table
Two Pointers

Merge two id-sorted lists of [id, value] pairs into one id-sorted list, adding the values of ids that appear in both.

Intuition

Both inputs are already sorted by id, which is exactly the setup of the merge step in merge sort.

Compare the ids at the two pointers. The smaller id cannot appear later in the other array, so it goes into the result as it is.

If the ids are equal, the id is shared: write it once with the two values added and move past it in both arrays.

Approach: Two pointers (merge step)

  1. Set i = 0, j = 0 and an empty result.
  2. While either array still has entries:
  3. If nums2 is used up, or nums1[i] has the smaller id, append nums1[i] and advance i.
  4. Else if nums1 is used up, or nums2[j] has the smaller id, append nums2[j] and advance j.
  5. Otherwise the ids are equal: append [id, nums1[i][1] + nums2[j][1]] and advance both.
  6. Return the result.

Step-by-step example

nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]
  1. ids 1 and 1 are equal: append [1, 2 + 4] = [1,6], move both.
  2. ids 2 and 3: 2 is smaller, append [2,3] from nums1.
  3. ids 4 and 3: 3 is smaller, append [3,2] from nums2.
  4. ids 4 and 4 are equal: append [4, 5 + 1] = [4,6], move both.
  5. Both arrays are used up. Return [[1,6],[2,3],[3,2],[4,6]].

Code: Python, Java, C++

1class Solution:
2    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:
3        i = j = 0
4        result = []
5        while i < len(nums1) or j < len(nums2):
6            if j == len(nums2) or (i < len(nums1) and nums1[i][0] < nums2[j][0]):
7                result.append(nums1[i])
8                i += 1
9            elif i == len(nums1) or nums2[j][0] < nums1[i][0]:
10                result.append(nums2[j])
11                j += 1
12            else:
13                result.append([nums1[i][0], nums1[i][1] + nums2[j][1]])
14                i += 1
15                j += 1
16        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

Every step moves at least one pointer forward, so there are at most n + m steps.

Space

O(1)

Only the two pointers, besides the output array.

Other approaches

Counting array over ids (time O(n + m + V), space O(V))

Ids are at most 1000, so add every value into an array indexed by id, then emit the non-zero ids in order. Simple, and it does not need the inputs to be sorted.

Hash map then sort (time O((n + m) log(n + m)), space O(n + m))

Sum values per id in a map, then sort the keys. Works for any id range but costs a sort.

Common mistakes

  • Stopping the loop when one array runs out and forgetting to copy the rest of the other.
  • Reading nums1[i] after i has reached the end; check the bounds before comparing ids.
  • Moving only one pointer when the ids are equal, which writes the shared id twice.
  • Writing the summed value back into an input row that the caller still uses; build a new pair instead.

Frequently asked questions

Why is the smaller id safe to append immediately?

The other array is sorted, so every id still ahead of its pointer is at least as large as its current id, which is already bigger. The smaller id can never show up there, so its value is final.

Is this the same as Merge Sorted Array?

It is the same merge pattern. The difference is that equal keys are combined into one entry instead of both being kept.

Can a value in the result be 0?

No. Every value is at least 1, and an id appears in the result only if it appears in at least one input.