File: merge-two-2d-arrays-by-summing-values/solution.py

Date: 2026-06-06

Time: 17:47

Purpose

This file solves LeetCode 2570: Merge Two 2D Arrays by Summing Values. It owns a single responsibility: merging two sorted arrays of [id, value] pairs into one sorted array, summing values when IDs match. It's the canonical merge step from merge sort, adapted for key-value pairs.

Key Components

merge_nums(nums1, nums2) -> list[list[int]]

The only function. Contract:

Patterns

Two-pointer merge. This is the textbook sorted-merge pattern: maintain one pointer per input, advance whichever points at the smaller key, and drain the remainder when one input is exhausted. The three-phase structure (main merge loop, drain nums1, drain nums2) is identical to the merge step in merge sort.

No hash maps, no defaultdict, no Counter — the solution exploits the sorted precondition to achieve O(n + m) time with O(1) auxiliary space (beyond the output list). This is the optimal approach when inputs are pre-sorted.

Dependencies

Imports: None. Pure Python, no standard library usage.

Imported by: Only its own testsolution.py. The "Imported By" list in the prompt is misleading — those are test files for *other* problems that happen to share a test harness or runner, not actual importers of mergenums.

Flow

1. Initialize result = [] and two pointers i, j = 0, 0.

2. Main loop (lines 16–24): while both pointers are in bounds, compare nums1[i][0] vs nums2[j][0]:

3. Drain loops (lines 25–30): append any remaining elements from whichever input wasn't fully consumed.

4. Return the merged result.

Data flows linearly — each element from both inputs is visited exactly once, and the output is built by appending in sorted order.

Invariants

Error Handling

None. The function trusts its inputs entirely — no bounds checking, no type validation, no handling of empty lists (which work correctly by falling through to the drain loops). This is appropriate for a LeetCode solution where inputs are guaranteed well-formed.

Topics to Explore

Beliefs