Merge Two 2D Arrays by Summing Values — LeetCode 2570 Python Solution

EasyArrayHash TableTwo Pointers
Problem
#2570
Reading time
2 min

The problem

You are given two 2D integer arrays nums1 and nums2. nums1[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali.

Example

Input
nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]
Output
[[1,6],[2,3],[3,2],[4,6]]
Explanation
The resulting array contains the following:

Python solution

Python
class Solution:
    def mergeArrays(
        self, nums1: List[List[int]], nums2: List[List[int]]
    ) -> List[List[int]]:
        cnt = Counter()
        for i, v in nums1 + nums2:
            cnt[i] += v
        return sorted(cnt.items())

Complexity

MeasureComplexity
TimeO(n + m)
SpaceO(M) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2570. Merge Two 2D Arrays by Summing Values is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2570. Merge Two 2D Arrays by Summing Values?
LeetCode 2570. Merge Two 2D Arrays by Summing Values is rated Easy on LeetCode.
What is the time complexity of LeetCode 2570. Merge Two 2D Arrays by Summing Values?
The Python solution on this page runs in O(n + m).
What is the space complexity of LeetCode 2570. Merge Two 2D Arrays by Summing Values?
The Python solution on this page uses O(M) auxiliary space.
What topics does LeetCode 2570. Merge Two 2D Arrays by Summing Values cover?
LeetCode 2570. Merge Two 2D Arrays by Summing Values is tagged Array, Hash Table and Two Pointers 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