2 POINTERS › TWO POINTER ON ARRAYS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The result must be sorted by id, and both input arrays already provide their ids in sorted order. Compare the first unprocessed pair in each array. If one id is smaller, it cannot match any later id in the other array, so you can place it in the result and move past it safely.
If the ids are equal, they describe the same identifier and must become one result pair with the two values added. When one array runs out, every remaining pair in the other array is already larger than everything you have processed, so you append those pairs without more comparisons.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n + m) | Each pointer only moves forward, and each input pair is inspected and appended at most once. Equal ids advance both pointers together, while disjoint ids still cause each pair to be consumed once, so even the worst case of no overlap remains linear. |
| Space | O(1) extra | The result is required output and is excluded. Apart from that output, the algorithm stores only two indices and a constant number of temporary values, so the working memory does not grow with n or m. |
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) {
vector<vector<int>> res;
int i = 0;
int j = 0;
while (i < nums1.size() && j < nums2.size()) {
if (nums1[i][0] < nums2[j][0]) {
res.push_back(nums1[i]);
i++;
} else if (nums1[i][0] > nums2[j][0]) {
res.push_back(nums2[j]);
j++;
} else {
res.push_back({nums1[i][0], nums1[i][1] + nums2[j][1]});
i++;
j++;
}
}
while (i < nums1.size()) {
res.push_back(nums1[i]);
i++;
}
while (j < nums2.size()) {
res.push_back(nums2[j]);
j++;
}
return res;
}
};The main loop stops as soon as either array is exhausted, which keeps every comparison valid. The two tail loops are not separate merging logic: once one side is empty, the remaining side is already sorted and cannot conflict with anything still unseen. In the equal-id branch, constructing a fresh pair is important because copying either input pair would discard one of the two values.