Merge Two 2D Arrays by Summing Values - Problem
You're tasked with merging two inventory lists from different warehouses! Each warehouse provides their data as a 2D array where each entry contains an [id, value] pair representing an item's ID and its quantity.
Your Mission: Combine these inventories into a single, consolidated list where:
- ๐ฆ Each item ID appears exactly once
- ๐ข The value for each ID is the sum of quantities from both warehouses
- ๐ The final list is sorted by ID in ascending order
- โจ If an item exists in only one warehouse, treat the other warehouse's quantity as
0
Input: Two 2D integer arrays nums1 and nums2, both already sorted by ID
Output: A merged 2D array sorted by ID with summed values
Example: If Warehouse A has [[1,2],[2,3]] and Warehouse B has [[1,4],[3,5]], the result should be [[1,6],[2,3],[3,5]]
Input & Output
example_1.py โ Basic merge with overlapping IDs
$
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 4 appears in both arrays: 5 + 1 = 6. IDs 2 and 3 appear in only one array each, so their values remain unchanged.
example_2.py โ No overlapping IDs
$
Input:
nums1 = [[2,4],[3,6],[5,5]]
nums2 = [[1,3],[4,3]]
โบ
Output:
[[1,3],[2,4],[3,6],[4,3],[5,5]]
๐ก Note:
No IDs overlap between the arrays, so we simply merge and sort all entries by ID. The result contains all unique IDs from both arrays.
example_3.py โ One array empty
$
Input:
nums1 = []
nums2 = [[1,1],[2,2]]
โบ
Output:
[[1,1],[2,2]]
๐ก Note:
When one array is empty, the result is simply the other array since there are no overlapping IDs to sum. The array is already sorted by ID.
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
Set up pointers
Each assistant points to the first item in their list
2
Compare item IDs
Look at the IDs both assistants are pointing to
3
Process smaller ID
If one ID is smaller, add that item to the master list and move that assistant forward
4
Sum equal IDs
If IDs are equal, add the item with combined quantities and move both assistants forward
5
Continue until done
Repeat until all items from both lists are processed
Key Takeaway
๐ฏ Key Insight: The two-pointer technique works perfectly here because both input arrays are already sorted, allowing us to merge them in linear time like the merge step in merge sort!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code