Merge Two 2D Arrays by Summing Values

Easy Topics Company Tags

Each row of nums1 and nums2 is [id, value]. Within each input, IDs are unique and appear in increasing order. Combine the two arrays into one array with a single row per ID. If an ID appears in both inputs, add its two values; otherwise keep its existing value. Return the rows in increasing ID order, including only IDs present in at least one input.

Example 1:

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

Output: [[1,8],[2,7],[4,2]]

Explanation: ID 1 appears in both inputs, so its value becomes 5 + 3 = 8. IDs 2 and 4 keep their values of 7 and 2. Return [[1,8],[2,7],[4,2]] in increasing ID order.

Example 2:

Input: nums1 = [[2,4]]
nums2 = [[5,6]]

Output: [[2,4],[5,6]]

Explanation: The inputs have no shared IDs. Keep both rows and order them by ID, giving [[2,4],[5,6]].

Example 3:

Input: nums1 = [[3,1000]]
nums2 = [[3,1000]]

Output: [[3,2000]]

Explanation: Both rows refer to ID 3. Their values add to 2000, so the result contains the single row [3,2000].

Constraints:

  • 1 <= nums1.length, nums2.length <= 200
  • Every row contains exactly two integers, [id, value].
  • 1 <= id, value <= 1000
  • IDs in each input are unique and strictly increasing.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.