Merge Two 2D Arrays by Summing Values - Problem
You are given two 2D integer arrays nums1 and nums2.
nums1[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali.
nums2[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali.
Each array contains unique ids and is sorted in ascending order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
- Only ids that appear in at least one of the two arrays should be included in the resulting array.
- Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be 0.
Return the resulting array. The returned array must be sorted in ascending order by id.
Input & Output
Example 1 — Basic Merge
$
Input:
nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]
›
Output:
[[1,6],[2,3],[3,2],[4,6]]
💡 Note:
ID 1 appears in both arrays: 2+4=6. ID 2 only in nums1: value 3. ID 3 only in nums2: value 2. ID 4 appears in both: 5+1=6.
Example 2 — No Common IDs
$
Input:
nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,2],[6,1]]
›
Output:
[[1,3],[2,4],[3,6],[4,2],[5,5],[6,1]]
💡 Note:
No common IDs, so we merge all pairs and sort by ID: 1,2,3,4,5,6.
Example 3 — Single Elements
$
Input:
nums1 = [[1,5]], nums2 = [[1,3]]
›
Output:
[[1,8]]
💡 Note:
Both arrays contain only ID 1, so we sum the values: 5+3=8.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 1000
- nums1[i].length == nums2[i].length == 2
- 1 ≤ idi, vali ≤ 1000
- Both arrays contain unique ids and are sorted in ascending order by id
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
Two sorted arrays with [id,value] pairs
2
Merge Process
Combine arrays, summing values for matching IDs
3
Sorted Output
Result array sorted by ID with summed values
Key Takeaway
🎯 Key Insight: Use two pointers to merge sorted arrays in O(n+m) time, like merging two sorted lists
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code