Merge Two 2D Arrays by Summing Values — LeetCode 2570 Python Solution
EasyArrayHash TableTwo Pointers
- Problem
- #2570
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n + m) |
| Space | O(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.