Merge Similar Items - Problem
You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array has the following properties:
items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item.
The value of each item in items is unique.
Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei.
Note: ret should be returned in ascending order by value.
Input & Output
Example 1 — Basic Merge
$
Input:
items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
›
Output:
[[1,6],[3,9],[4,5]]
💡 Note:
Value 1: weight 1 + 5 = 6. Value 3: weight 8 + 1 = 9. Value 4: weight 5. Sorted by value: [1,6], [3,9], [4,5].
Example 2 — No Overlap
$
Input:
items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[4,5],[6,4]]
›
Output:
[[1,1],[2,4],[3,2],[4,5],[6,4]]
💡 Note:
Only value 2 appears in both arrays: 3 + 1 = 4. All other values appear once. Final sorted result.
Example 3 — Single Items
$
Input:
items1 = [[1,3]], items2 = [[2,2]]
›
Output:
[[1,3],[2,2]]
💡 Note:
No overlapping values, so result contains both items as-is, sorted by value.
Constraints
- 1 ≤ items1.length, items2.length ≤ 1000
- items1[i].length == items2[i].length == 2
- 1 ≤ valuei, weighti ≤ 1000
- Each valuei in items1 is unique
- Each valuei in items2 is unique
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
Two separate item arrays with [value, weight] pairs
2
Merge Process
Combine items with same values, sum their weights
3
Sorted Output
Return merged items sorted by value ascending
Key Takeaway
🎯 Key Insight: Use a hash map to efficiently group items by value and sum their weights in a single pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code