Merge Similar Items — LeetCode 2363 Python Solution
- Problem
- #2363
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties: items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item.
Example
- Input
- items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
- Output
- [[1,6],[3,9],[4,5]]
- Explanation
- The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.
Python solution
class Solution:
def mergeSimilarItems(
self, items1: List[List[int]], items2: List[List[int]]
) -> List[List[int]]:
cnt = Counter()
for v, w in chain(items1, items2):
cnt[v] += w
return sorted(cnt.items())Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + m) |
| Space | O(n + m), where n and m are the lengths of `items1` and `items2` respectively auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2363. Merge Similar Items is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2363. Merge Similar Items?
- LeetCode 2363. Merge Similar Items is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2363. Merge Similar Items?
- The Python solution on this page runs in O(n + m).
- What is the space complexity of LeetCode 2363. Merge Similar Items?
- The Python solution on this page uses O(n + m), where n and m are the lengths of `items1` and `items2` respectively auxiliary space.
- What topics does LeetCode 2363. Merge Similar Items cover?
- LeetCode 2363. Merge Similar Items is tagged Array, Hash Table, Ordered Set and Sorting on LeetCode.