Merge Two 2D Arrays by Summing Values

Updated on 17 June, 2025
Merge Two 2D Arrays by Summing Values header image

Problem Statement

In this task, you are presented with two 2D integer arrays, nums1 and nums2. Each element in these arrays is a pair representing an identifier and its associated value. The arrays are guaranteed to have each identifier appearing uniquely and are sorted based on the identifier values in ascending order.

The objective is to merge these two arrays into a single array that also maintains ascending order by identifier. However, there is a specific merging criterion to follow:

  • Include all identifiers that appear in at least one of the arrays.
  • For each identifier, its corresponding value in the merged array should be the sum of its values from nums1 and nums2. If an identifier is present in only one array, the value from the other array should be considered as 0.

The resulting array should consequently be a collection of identifier-value pairs, sorted by the identifiers in ascending order.

Examples

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:

The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.

Example 2

Input:

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

Output:

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

Explanation:

There are no common ids, so we just include each id with its value in the resulting list.

Constraints

  • 1 <= nums1.length, nums2.length <= 200
  • nums1[i].length == nums2[j].length == 2
  • 1 <= idi, vali <= 1000
  • Both arrays contain unique ids.
  • Both arrays are in strictly ascending order by id.

Approach and Intuition

To solve the problem of merging the two arrays while summing the values of common identifiers, the approach involves iterating through both arrays simultaneously and comparing their current identifiers. Here’s a step-by-step breakdown:

  1. Initialize pointers for both arrays, nums1 and nums2, starting from the beginning.
  2. Create an empty result list to store the merged output.
  3. Loop through both arrays until you have processed all elements in both arrays:
    • Compare the current identifiers from both arrays.
    • If the identifiers are the same, add a new pair to the result list with this identifier and the sum of both values, and move both pointers forward.
    • If the identifier from nums1 is smaller, add a new pair to the result list with this identifier and its corresponding value, then move the pointer for nums1 forward.
    • If the identifier from nums2 is smaller, perform the corresponding action as the above but for nums2.
  4. After exiting the loop, check if there are remaining elements in either nums1 or nums2 and add them to the result with their values, as the remaining identifiers will not have counterparts in the other array.

This algorithm is efficient given that both arrays are already sorted by identifiers, allowing for a linear time complexity relative to the sum of the lengths of both arrays. The worst-case space complexity is also linear relative to the output size, which in the worst case could be as large as the sum of the lengths of both input arrays.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    vector<vector<int>> combineArrays(vector<vector<int>>& array1, vector<vector<int>>& array2) {
        int size1 = array1.size(), size2 = array2.size();
        int index1 = 0, index2 = 0;
    
        vector<vector<int>> resultArray;
        while (index1 < size1 && index2 < size2) {
            if (array1[index1][0] == array2[index2][0]) {
                resultArray.push_back({array1[index1][0], array1[index1][1] + array2[index2][1]});
                index1++;
                index2++;
            } else if (array1[index1][0] < array2[index2][0]) {
                resultArray.push_back(array1[index1]);
                index1++;
            } else {
                resultArray.push_back(array2[index2]);
                index2++;
            }
        }
    
        while (index1 < size1) {
            resultArray.push_back(array1[index1]);
            index1++;
        }
    
        while (index2 < size2) {
            resultArray.push_back(array2[index2]);
            index2++;
        }
    
        return resultArray;
    }
};

Merge two 2D arrays based on their first element and sum their second elements when the first elements match. In the provided C++ code, here is how you achieve this:

  1. Initialize indices (index1, index2) to 0 to traverse both array1 and array2.
  2. Create an empty 2D vector resultArray to store the merged results.
  3. Use a while loop to iterate through both arrays until one or both of the arrays are fully traversed.
    • If the first elements of the current row in both arrays match, add a new row to resultArray. The first element is the matched element, and the second element is the sum of the second elements from both arrays. Increment both indices.
    • If the first element of the current row in array1 is less than array2, add the entire row from array1 to resultArray and increment index1.
    • If the first element of the current row in array1 is greater, add the entire row from array2 to resultArray and increment index2.
  4. After the main loop, one or both arrays might still have elements left to process. Continue adding all remaining rows from array1 or array2 to resultArray using separate while loops, updating indices as needed.

This method ensures that resultArray contains elements from both arrays combined based on their first elements, and sums their second elements when appropriate, retaining the order of the non-matching rows.

java
class Solution {
    
    public int[][] combineArrays(int[][] firstArray, int[][] secondArray) {
        int len1 = firstArray.length, len2 = secondArray.length;
        int index1 = 0, index2 = 0;
    
        List<int[]> combinedResult = new ArrayList<>();
        while (index1 < len1 && index2 < len2) {
            if (firstArray[index1][0] == secondArray[index2][0]) {
                combinedResult.add(
                    new int[] {
                        firstArray[index1][0],
                        firstArray[index1][1] + secondArray[index2][1],
                    }
                );
                index1++;
                index2++;
            } else if (firstArray[index1][0] < secondArray[index2][0]) {
                combinedResult.add(firstArray[index1]);
                index1++;
            } else {
                combinedResult.add(secondArray[index2]);
                index2++;
            }
        }
    
        while (index1 < len1) {
            combinedResult.add(firstArray[index1]);
            index1++;
        }
    
        while (index2 < len2) {
            combinedResult.add(secondArray[index2]);
            index2++;
        }
    
        int[][] finalResult = new int[combinedResult.size()][2];
        for (int i = 0; i < combinedResult.size(); i++) {
            finalResult[i] = combinedResult.get(i);
        }
    
        return finalResult;
    }
}

The provided Java code addresses the task of merging two 2D integer arrays by summing their corresponding values based on a specific criterion. In this method named combineArrays, two 2D input arrays firstArray and secondArray are merged together. Each inner array within these 2D arrays is expected to consist of two elements, typically representing a key-value pair.

  • Firstly, initialize pointers index1 and index2 for each array, as well as a list combinedResult to hold the merged results.
  • Iterate through both arrays simultaneously using a while loop, comparing their first elements (which act as keys).
  • If the keys match, create a new entry with the same key and the sum of the values from both arrays, then add this entry to combinedResult. Increment both pointers.
  • If the keys do not match, add the entry with the smaller key to combinedResult and increment the respective pointer.
  • In case there are remaining entries in either array after one array is exhausted, add these remaining entries directly to combinedResult.
  • Convert the ArrayList to a 2D array finalResult, preserving the structure required for the output, and return finalResult.

With this method, you seamlessly merge two datasets where the integration of values depends on matching keys. The logic ensures that all entries are considered and correctly combined or kept separate based on their keys, thus providing a comprehensive solution to the problem of merging data with conditional aggregation.

python
class Solution:
    def merge_lists(
        self, list1: list[list[int]], list2: list[list[int]]
    ) -> list[list[int]]:
        length1, length2 = len(list1), len(list2)
        index1, index2 = 0, 0
    
        combined_list = []
        while index1 < length1 and index2 < length2:
            if list1[index1][0] == list2[index2][0]:
                combined_list.append(
                    [list1[index1][0], list1[index1][1] + list2[index2][1]]
                )
                index1 += 1
                index2 += 1
            elif list1[index1][0] < list2[index2][0]:
                combined_list.append(list1[index1])
                index1 += 1
            else:
                combined_list.append(list2[index2])
                index2 += 1
    
        while index1 < length1:
            combined_list.append(list1[index1])
            index1 += 1
    
        while index2 < length2:
            combined_list.append(list2[index2])
            index2 += 1
    
        combined_list = [combined_list[i] for i in range(len(combined_list))]
    
        return combined_list

Merge two 2-dimensional arrays by summing their values when corresponding indices match using Python. The provided Python code defines a class Solution with a method merge_lists to handle this functionality.

First, this method initializes counters for both lists and an empty list to store the merged results. It processes both input lists in parallel using while loops. When the first elements (indices) of the sublists from both lists match, it sums the second elements and stores the result in the combined_list. If they do not match, it appends the smaller element based on the first value and increments the respective index.

Once one list is completely processed and if any elements remain in the other list, the remaining elements of that list are appended directly to combined_list.

This solution effectively merges two 2D lists by comparing and combining their elements based on the conditions provided, ensuring all elements are considered and correctly merged. This method is efficient for merging lists where matching and summing based on specific criteria are required.

Comments

No comments yet.