Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Sorting
Merge Two 2D Arrays By Summing Values

Merge two sorted 2D arrays of key-value pairs by combining equal keys and summing their values.

Acceptance 0%
Problem Statement

Merge Two 2D Arrays By Summing Values

You are given two 2D integer arrays, nums1 and nums2. Each array contains rows of the form [id, value], where id is a unique key within that array.

Create a new 2D array that contains every distinct id appearing in either input array. For each id, its output value should be the sum of the values from both arrays for that id.

Return the result sorted by id in strictly increasing order.

Notes

  • If an id appears in only one array, use its value as-is.
  • The output should contain one row per distinct id.
  • The input arrays are commonly already sorted by id, but the result must be sorted as well.

Input Format

  • nums1: a 2D array of pairs [id, value]
  • nums2: a 2D array of pairs [id, value]

Each pair represents one key-value entry.

Output Format

Return a 2D array of pairs [id, mergedValue] sorted by id.

Constraints

  • Each row has exactly 2 integers.
  • id values are distinct within the same array.
  • The merged result must include every distinct id from both arrays.
  • Sort output rows by id ascending.
Examples
Sample cases returned by the problem API.

Example 1

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

Combine values for matching ids: 1 -> 2 + 4 = 6, 4 -> 5 + 1 = 6. Keys 2 and 3 appear in only one array.

Example 2

Input

nums1 = [[2,4]], nums2 = [[1,3],[2,1],[5,7]]

Output

[[1,3],[2,5],[5,7]]

Explanation

The merged array contains all distinct ids, with values summed where ids overlap.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.