#2363
Merge Similar Items
EasyArrayHash TableSortingOrdered SetHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a hash map allows us to efficiently aggregate weights by value from both arrays in a single pass. This reduces the time complexity significantly compared to the brute force method.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a hash map to store the weights.
- 2Step 2: Iterate through items1 and add weights to the map using values as keys.
- 3Step 3: Repeat for items2, updating the weights in the map.
- 4Step 4: Convert the map to a list and sort it by value.
- 5Step 5: Return the sorted list.
solution.py10 lines
1def mergeSimilarItems(items1, items2):
2 from collections import defaultdict
3 weights = defaultdict(int)
4 for value, weight in items1:
5 weights[value] += weight
6 for value, weight in items2:
7 weights[value] += weight
8 return sorted(weights.items())
9
10print(mergeSimilarItems([[1,1],[4,5],[3,8]], [[3,1],[1,5]]))ℹ
Complexity note: The time complexity is O(n) because we make a single pass through both arrays to populate the hash map. The space complexity is O(n) due to the storage of weights in the hash map.
- 1Using a hash map allows for efficient aggregation of weights.
- 2Sorting the final result ensures the output is in the correct order.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.