Problem Description
Given two 2D integer arrays, each holding unique ids sorted in ascending order along with their corresponding values, merge them into a single sorted 2D array. If an id appears in both arrays, the resulting value is the sum of values from both arrays. If an id appears in only one array, its value remains unchanged.
Key Insights
- Both input arrays are sorted by id, which allows for an efficient merge using the two pointers technique.
- Since the arrays are sorted, we can iterate over both simultaneously without additional data structures.
- A hash table (or dictionary) approach is an alternative, but the two pointers method leverages the sorted property for O(n) merging.
Space and Time Complexity
Time Complexity: O(n + m), where n and m are the lengths of nums1 and nums2. Space Complexity: O(n + m), accounting for the space needed for the resulting merged array.
Solution
We use the two pointers approach:
- Initialize two pointers, one for each array.
- Compare the current id from each array:
- If the ids match, sum their values and add the pair to the result, then advance both pointers.
- If one id is smaller, add that pair to the result and advance its pointer.
- Append any remaining pairs from either array once the other pointer has reached the end. This approach leverages the fact that both arrays are already sorted, ensuring a linear time merge with constant extra space (besides the output storage).