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
Merge Similar Items INPUT items1: [1,1] [4,5] [3,8] val:1 val:4 val:3 items2: [3,1] [1,5] val:3 val:1 Format: [value, weight] Common values: 1, 3 Unique to items1: 4 = needs merging ALGORITHM STEPS 1 Create Hash Map map = {} 2 Process items1 Add all to map map after items1: 1 --> 1 4 --> 5 3 --> 8 +5 = 6 +1 = 9 (after items2 merge) 3 Process items2 Add/merge weights 4 Sort by Value Keys: 1, 3, 4 (sorted) Time: O(n log n) Space: O(n) FINAL RESULT Merged Array (sorted): [1, 6] 1+5 = 6 [3, 9] 8+1 = 9 [4, 5] 5 (unique) Output: [[1,6],[3,9],[4,5]] OK - Verified! Sorted by value ascending Key Insight: Use a Hash Map to efficiently track and merge weights by value. The map provides O(1) lookup for checking if a value exists. When processing items2, either add new entries or sum weights to existing values. Final sorting ensures ascending order by value as required. TutorialsPoint - Merge Similar Items | Hash Map Approach
Asked in
Amazon 25 Google 18 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen