Leetcode 2570. Merge Two 2D Arrays by Summing Values
Given two 2D integer arrays nums1
and nums2
, each array contains elements in the form [id, val]
where:
id
is a unique identifier,val
is the value associated with the identifier.Merge these two arrays such that the resulting array contains unique id
s and sums the val
for any id
that appears in both arrays. The resulting array should be sorted by id
.
Example:
Input: nums1 = [[1, 2], [2, 3], [4, 5]], nums2 = [[1, 3], [2, 1], [3, 2]]
Output: [[1, 5], [2, 4], [3, 2], [4, 5]]
id
s, no missing id
or val
, etc.)?id
s: Should the input lists be considered pre-sorted, or can they be unordered? (Clarification: In the resulting array, id
s must be sorted.)id
as key and the val
as the cumulative value.id
s.id
.#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<vector<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) {
unordered_map<int, int> idMap;
// Aggregate values from nums1
for (const auto& pair : nums1) {
idMap[pair[0]] += pair[1];
}
// Aggregate values from nums2
for (const auto& pair : nums2) {
idMap[pair[0]] += pair[1];
}
vector<vector<int>> result;
for (const auto& entry : idMap) {
result.push_back({entry.first, entry.second});
}
// Sort by id
sort(result.begin(), result.end(), [](const vector<int>& a, const vector<int>& b) {
return a[0] < b[0];
});
return result;
}
n
is the length of nums1
and m
is the length of nums2
.k
is the number of unique ids.k
is the number of unique ids (because it is sorted by id
).This solution efficiently aggregates and sorts the values, making it suitable for this kind of merging task. By using an unordered map, we ensure an average case constant time complexity for insertions and lookups.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?