Merge Sorted Array
Algorithm/TwoPointers
Intuition
The goal is to merge two sorted arrays into a single sorted array. The solution merges the arrays in-place and without needing extra space.
Approach
Below is the step-by-step breakdown of the approach:
-
Two Pointers (from the end):
- Use two pointers, i and j, to iterate through
nums1
andnums2
from the end of each valid part . - Use a third pointer k to place elements into the correct position in
nums1
. This pointer starts from the last index (k = m + n - 1).
- Use two pointers, i and j, to iterate through
-
Merge Process:
- Compare elements from
nums1[i]
andnums2[j]
. Place the larger element atnums1[k]
. - Decrement the corresponding pointer (i, j, or k) after placing an element.
- Continue the comparison until all elements from
nums2
have been merged intonums1
.
- Compare elements from
-
Remaining Elements:
- If
nums2
has remaining elements, directly copy them tonums1
. - If
nums1
still has remaining elements, they are already in place, so no further action is needed.
- If
Complexity
- Time Complexity:, the merging process requires iterating through all elements in
nums1
andnums2
. - Space Complexity: , the solution uses only a constant amount of extra space apart from the input arrays.