Merge Two 2D Arrays by Summing Values

You are given two 2D integer arrays `nums1` and `nums2`, where each `nums[i] = [id, val]` says the number with that `id` has value `val`. Each array has unique ids and is sorted in ascending order by id. Merge them into one array sorted by id: every id that appears in either array appears once, and its value is the sum of its values in both arrays (an id missing from one array counts as 0 there).

30:00

Merge Two 2D Arrays by Summing Values
easy
Free written solution
Topics
Companies

You are given two 2D integer arrays nums1 and nums2, where each nums[i] = [id, val] says the number with that id has value val. Each array has unique ids and is sorted in ascending order by id.

Merge them into one array sorted by id: every id that appears in either array appears once, and its value is the sum of its values in both arrays (an id missing from one array counts as 0 there).

Example 1:
Input: {"nums1":[[1,2],[2,3],[4,5]],"nums2":[[1,4],[3,2],[4,1]]}
Output: [[1,6],[2,3],[3,2],[4,6]]
Constraints:
  • 1≤nums1.length,nums2.length≤2001 \leq \text{nums1.length}, \text{nums2.length} \leq 200

  • nums1[i].length == nums2[j].length == 2

  • 1≤idi,vali≤10001 \leq id_i, val_i \leq 1000

  • Both arrays contain unique ids and are sorted by id in strictly ascending order.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums1":[[1,2],[2,3],[4,5]],"nums2":[[1,4],[3,2],[4,1]]}

nums1 has 3 pairs and nums2 has 3, both sorted by id. Merge them like the merge step of merge sort, adding values when an id appears in both.

nums1 (3)

id 1
2

i

id 2
3

id 4
5

nums2 (3)

id 1
4

j

id 3
2

id 4
1

i = 0 (id 1)
j = 0 (id 1)

next compare: 1 vs 1

result (0)

empty

from nums1 only

from nums2 only

id in both, values added

Variables
VariableValue
len(nums1)3
len(nums2)3
DepthFunction Call
Stack empty
0/6