2570. Merge Two 2D Arrays by Summing Values - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

You are given two 2D integer arrays, nums1 and nums2, where each element is in the form [id, value]. Each array represents a collection of pairs with unique ids within that array. Your task is to merge these two arrays by summing the values for pairs that have the same id. The result should be a 2D array where each element is [id, totalValue], and the array is sorted in ascending order by id.

For example, if:

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

Then the merged result should be:

  • [[1, 6], [2, 3], [3, 2], [4, 6]]

Explanation:

  • For id = 1: 2 (from nums1) + 4 (from nums2) = 6
  • For id = 2: Only present in nums1 with value 3
  • For id = 3: Only present in nums2 with value 2
  • For id = 4: 5 (from nums1) + 1 (from nums2) = 6

Hints

  1. Using a Hash Map / Dictionary:
    You can use a hash map to record the sum of values for each id. Iterate through both arrays, update the sum for each id, and then convert the map back into a sorted 2D array.

  2. Using Two Pointers (Merge Technique):
    Since each input array is sorted by id, you can use a two-pointer approach to merge them in one pass. Compare the current id from both arrays:

    • If they are equal, sum the values.
    • If one id is smaller, append that pair as is and move the corresponding pointer.
    • Continue until all pairs from both arrays are processed.

Approaches

Approach 1: Hash Map / Dictionary

  • Steps:
    1. Create an empty dictionary.
    2. Iterate over each pair in nums1 and add its value to the dictionary using the id as the key.
    3. Iterate over each pair in nums2 and update the dictionary by adding to the existing value (or inserting a new key if not present).
    4. Extract the dictionary items, sort by id, and construct the final 2D array.
  • Complexity:
    • Time: O(n₁ + n₂ + k log k) where n₁ and n₂ are the lengths of nums1 and nums2 respectively and k is the number of unique ids.
    • Space: O(k)

Approach 2: Two Pointers (Merge Technique)

  • Steps:
    1. Initialize two pointers for nums1 and nums2.
    2. Compare the ids at the pointers:
      • If equal, sum the values, add the pair to the result, and move both pointers.
      • If one id is smaller, add that pair to the result and move that pointer.
    3. Append the remaining pairs from the array that is not yet fully processed.
  • Complexity:
    • Time: O(n₁ + n₂) because each array is traversed once.
    • Space: O(1) extra space (excluding the output array).

Complexity Analysis

  • Time Complexity:
    The two approaches yield efficient solutions. The hash map approach has an extra sorting step but is still efficient if the number of unique ids is small. The two pointers approach leverages the sorted order for linear time merging.

  • Space Complexity:
    The hash map approach uses extra space proportional to the number of unique ids. The two pointers approach uses minimal extra space.

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Step-by-Step Walkthrough and Visual Examples

  1. Initialization:

    • For the hash map approach, initialize an empty dictionary (or TreeMap in Java).
  2. Processing nums1:

    • Iterate through each pair in nums1. For instance, for [1, 2], add key 1 with value 2.
    • For [2, 3], add key 2 with value 3.
    • For [4, 5], add key 4 with value 5.
  3. Processing nums2:

    • Iterate through each pair in nums2. For [1, 4], update key 1: 2 + 4 = 6.
    • For [3, 2], add key 3 with value 2.
    • For [4, 1], update key 4: 5 + 1 = 6.
  4. Final Merge:

    • The dictionary now contains: {1: 6, 2: 3, 3: 2, 4: 6}.
    • Sort the keys (if not using a TreeMap, which is naturally sorted).
    • Construct the output array: [[1, 6], [2, 3], [3, 2], [4, 6]].
  5. Result:

    • The merged 2D array is returned, which has the summed values for each unique id.

Common Mistakes

  • Overwriting Instead of Summing:
    Ensure that when an id appears in both arrays, you add the values rather than overwriting them.

  • Forgetting to Sort:
    The final result must be sorted by id. Using a TreeMap in Java or sorting the keys in Python guarantees this.

  • Handling Empty Inputs:
    Consider edge cases where one or both arrays are empty.

Edge Cases

  • One Array is Empty:
    If either nums1 or nums2 is empty, simply return the other array (after ensuring it is sorted by id if necessary).

  • No Overlapping Ids:
    If the arrays have no common ids, the merged result is just the union of both arrays, sorted by id.

  • Large Input Sizes:
    Ensure the chosen approach scales efficiently with large arrays.

Alternative Variations

  • Different Merge Operations:
    Instead of summing values, you might be asked to perform other operations (e.g., maximum, minimum, or multiplication) for overlapping ids.

  • Unsorted Input Arrays:
    If the input arrays are not guaranteed to be sorted, you would need to sort the result before returning it.

TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;