88. Merge Sorted Array
Efficiently Merging Two Sorted Arrays in JavaScript
Introduction
When working with arrays in JavaScript, a common task is to merge two sorted arrays into one sorted array. This challenge is frequently encountered in coding interviews and competitive programming. Today, we'll explore an efficient and elegant solution to this problem using a two-pointer technique.
Problem Statement
You are given two sorted integer arrays nums1
and nums2
, where nums1
has a size of m + n
to accommodate the elements of nums2
at its end. Our goal is to merge these arrays into a single sorted array in place.
Intuition
The arrays are already sorted, so we can leverage this property to our advantage. By starting from the end of both arrays, we can efficiently place the largest elements at the end of nums1
, ensuring the array remains sorted. This approach minimizes the need for additional space and makes the merging process straightforward.
Approach
Initialize Pointers:
i
points to the last element of the valid entries innums1
(m - 1
).j
points to the last element ofnums2
(n - 1
).k
points to the last position of the merged array innums1
(m + n - 1
).
Merge Process:
Use a while loop to iterate until all elements in
nums2
are processed (j >= 0
).Compare elements from the end of both arrays:
If
nums1[i]
is greater than or equal tonums2[j]
, placenums1[i]
at positionk
and decrementi
.Otherwise, place
nums2[j]
at positionk
and decrementj
.
Decrement
k
after placing each element.
This ensures that the larger elements are placed correctly from the end, thus sorting the merged array in place without needing extra space.
Code Implementation
Here's the JavaScript code to achieve this:
var merge = function(nums1, m, nums2, n) {
let i = m - 1;
let j = n - 1;
let k = m + n - 1;
while(j >= 0) {
if(i >= 0 && nums1[i] >= nums2[j]) {
nums1[k] = nums1[i];
i--;
} else {
nums1[k] = nums2[j];
j--;
}
k--;
}
};
Complexity Analysis
Time Complexity:
The algorithm makes a single pass through both arrays, ensuring each element is processed exactly once.
Space Complexity:
The merging is done in place within
nums1
, so no additional space is required.
Conclusion
By leveraging the two-pointer technique, we efficiently merge two sorted arrays in place with optimal time and space complexity. This method ensures that we only make one pass through each array, making it both time-efficient and space-efficient. This approach is not only elegant but also practical for real-world applications where managing memory is crucial.
For more insights and detailed solutions, you can check out this discussion on LeetCode: Merge Sorted Array - LeetCode.
I hope this solution helps you understand how to merge sorted arrays efficiently. Feel free to try this code on your own and tweak it as necessary. Happy coding! š
Comments
Post a Comment