Merge Similar Items - Problem
You're managing an inventory consolidation system for a warehouse. You have two separate lists of items from different sources, and you need to merge them intelligently!
Given two 2D integer arrays items1 and items2, where each represents a collection of items:
- Each item is represented as
[value, weight] - The
valueis a unique identifier for the item type - The
weightrepresents the quantity/weight of that item - Important: Each value appears at most once in each array
Your Goal: Merge both inventories by combining items with the same value (adding their weights together) and return the result sorted by value in ascending order.
Example: If items1 = [[1,1],[4,5]] and items2 = [[1,8],[3,1]], then items with value 1 should be combined: weight 1 + 8 = 9.
Input & Output
example_1.py โ Basic Merge
$
Input:
items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
โบ
Output:
[[1,6],[3,9],[4,5]]
๐ก Note:
Item with value 1: weight 1+5=6. Item with value 3: weight 8+1=9. Item with value 4: only in items1, weight=5. Result sorted by value.
example_2.py โ No Overlap
$
Input:
items1 = [[1,1],[3,2]], items2 = [[2,3],[4,2]]
โบ
Output:
[[1,1],[2,3],[3,2],[4,2]]
๐ก Note:
No items have the same value, so we simply combine both arrays and sort by value: 1,2,3,4.
example_3.py โ Complete Overlap
$
Input:
items1 = [[1,3],[2,2]], items2 = [[1,2],[2,1]]
โบ
Output:
[[1,5],[2,3]]
๐ก Note:
All items have matching values. Item 1: 3+2=5, Item 2: 2+1=3. Both arrays contribute to each result item.
Constraints
- 1 โค items1.length, items2.length โค 1000
- items1[i].length == items2[i].length == 2
- 1 โค valuei, weighti โค 1000
- Each value in items1 and items2 is unique within its respective array
Visualization
Tap to expand
Understanding the Visualization
1
Receive Shipments
Two suppliers deliver their inventory lists with product codes and quantities
2
Create Master Ledger
Use a ledger (hash map) to track total quantities for each product code
3
Process First Supplier
Add all items from first supplier to the ledger
4
Process Second Supplier
For each item, either add quantity to existing entry or create new entry
5
Generate Final Catalog
Convert ledger to sorted list by product code
Key Takeaway
๐ฏ Key Insight: Hash maps provide O(1) lookup and update operations, making them perfect for merging operations where you need to combine values with the same key efficiently.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code