Problem Description
Given two sorted arrays nums1 and nums2, where nums1 has enough space to hold all elements of nums2, merge nums2 into nums1 so that nums1 becomes a single sorted array.
Key Insights
- Both arrays are already sorted in non-decreasing order.
- The merge should be done in-place into nums1.
- Start merging from the end to avoid overwriting elements in nums1.
- Use two pointers, one for nums1 and one for nums2, and a tail pointer for placement.
Space and Time Complexity
Time Complexity: O(m + n)
Space Complexity: O(1)
Solution
We use a two-pointer approach starting from the end of both arrays. Initialize three pointers:
- p1 pointing to the last valid element in nums1.
- p2 pointing to the last element in nums2.
- tail pointing to the last index of nums1.
While both pointers are valid, compare the elements pointed by p1 and p2, placing the larger element at the tail position. Decrement the corresponding pointer and the tail pointer. Finally, if any elements remain in nums2 (i.e., p2 >= 0), copy them over into nums1. This solution leverages the extra space at the end of nums1 and ensures the merge is done in-place in linear time.