Merge Similar Items — LeetCode 2363 Python Solution

EasyArrayHash TableOrdered SetSorting
Problem
#2363
Pattern
Sorting
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n + m)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview