⚡Flashcard Drill➔
NeetCode #182LC-2570EasyTwo Pointers
← Back to All Problems

#182 · #2570 · Merge Two 2D Arrays by Summing Values(合并两个二维数组 - 求和法)

📌 Problem Statement & Constraints

You are given two 2D integer arrays nums1 and nums2, each [id_i, val_i], sorted by id with distinct ids. Merge them by summing the values of equal ids, keeping the result sorted by id. Constraints: 1 <= nums1.length, nums2.length <= 200, 1 <= id <= 1000, 1 <= val <= 100. The result must not contain ids with a sum of zero.

💡 Core Algorithmic Approaches

  1. Because both arrays are sorted by id, a two-pointer merge handles the join directly.
  2. When the ids are equal, sum the values and advance both pointers.
  3. When one id is smaller, emit that entry alone and advance only that pointer.
  4. Finally, append any remaining tail. Since all values are positive, no sum can be zero, so no filtering is needed -- but the problem's general form asks for it, so guard anyway if values could be negative.

💻 Benchmark Python3 Implementation

class Solution:
    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:
        i = j = 0
        res = []
        while i < len(nums1) and j < len(nums2):
            a, b = nums1[i], nums2[j]
            if a[0] == b[0]:
                res.append([a[0], a[1] + b[1]])   # equal ids -> sum
                i += 1
                j += 1
            elif a[0] < b[0]:
                res.append(a)
                i += 1
            else:
                res.append(b)
                j += 1
        res.extend(nums1[i:])          # remaining tails (at most one is non-empty)
        res.extend(nums2[j:])
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m + n): each entry is visited once.
💾 Space Complexity
O(m + n) for the result.

⚠️ Interview Pitfalls & Follow-ups

  • Using a hash map and then sorting: correct but O((m+n) log(m+n)); the sorted inputs make the two-pointer merge linear.
  • Advancing only one pointer when the ids are equal: both must advance.
  • Forgetting to append the tails: after the loop, one array may still have unprocessed entries.
  • Assuming the values are positive: the constraints say they are, so zero sums cannot occur -- but in a generalised version you would filter them out.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Two Pointers Problems

中文速览与面试要点

合并两个二维数组 - 求和法

给你两个 二维 整数数组 nums1 和 nums2: nums1[i] = [idi, vali] 表示编号为 idi 的数字对应的值等于 vali;每个数组都按 id 升序 排列,且同一数组内所有 id 互不相同 。请你将两个数组合并为一个按 id 升序排列的数组,合并规则如下:只有在两个数组都存在的 id 才能合并为一个 id 对应的值之和;只在一个数组中存在的 id 直接保留。返回合并后的数组。约束:1 ≤ nums1.length, nums2.length ≤ 200;nums1[i].length == nums2[j].length == 2;1 ≤ idi, vali ≤ 1000;每个数组内的 id 严格递增。

核心要点

  • 归并双指针(标准解) :i、j 分别遍历两个数组。比较 nums1[i][0] 与 nums2[j][0] :相等则值相加;谁小取谁。
  • 为什么用双指针而非哈希表 :两个数组都已按 id 升序,归并可以在 O(m+n) 内完成且 天然保持有序 ;哈希表需要额外排序,是 O((m+n) log(m+n))。
  • 处理剩余部分 :当一方遍历完后,把另一方的剩余元素直接追加到结果末尾(它们已有序)。
  • 结果有序性 :归并过程保证按 id 升序输出,无需额外排序。

常见陷阱

  • 用哈希表合并后再排序 :可行但复杂度更高。题目明确给出「已按 id 升序」,应利用归并的线性优势。
  • 忘记处理剩余元素 :只写 while 循环会导致较长数组的尾部丢失。
  • id 相等时只取一个值 :题目要求 求和 。
  • 结果未保持有序 :若用哈希表实现且忘记排序,结果顺序会随机。

参考实现

class Solution:
    def mergeArrays(self, nums1: list[list[int]], nums2: list[list[int]]) -> list[list[int]]:
        i = j = 0
        res = []
        while i < len(nums1) and j < len(nums2):
            if nums1[i][0] == nums2[j][0]:
                res.append([nums1[i][0], nums1[i][1] + nums2[j][1]])
                i += 1
                j += 1
            elif nums1[i][0] < nums2[j][0]:
                res.append(nums1[i])
                i += 1
            else:
                res.append(nums2[j])
                j += 1
        res.extend(nums1[i:])       # 剩余部分已有序,直接追加
        res.extend(nums2[j:])
        return res