88. Merge Sorted Array
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core task is to merge two sorted integer arrays, nums2 into nums1, in-place. The array nums1 has a total length of m + n, with the last n elements being empty slots (represented by zeros) to accommodate the elements from nums2. A naive approach of merging from the beginning of the arrays would require shifting elements in nums1 to make space, which is inefficient. The key insight is to utilize the empty space at the end of nums1 and fill the merged array from back to front.
Solution
Merge Sorted Array in Python
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# Initialize p1 to the last valid element of nums1, p2 to the last element of nums2.
p1 = m - 1
p2 = n - 1
# Initialize p to the last index of nums1 (the merge destination).
p = m + n - 1
# Loop backwards from the end of both arrays as long as there are elements in nums2.
while p2 >= 0:
# If p1 is still valid and the element in nums1 is greater than in nums2.
if p1 >= 0 and nums1[p1] > nums2[p2]:
# Place the larger element (from nums1) at the end of the merged list.
nums1[p] = nums1[p1]
p1 -= 1
else:
# Place the element from nums2 (it's larger or no more elements in nums1).
nums1[p] = nums2[p2]
p2 -= 1
# Move to the next position to fill.
p -= 1
# Elements remaining at the beginning of nums1 are already in their correct sorted position.
Merge Sorted Array in Java
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
// Initialize p1 to the end of the initial elements in nums1,
// p2 to the end of nums2, and p to the end of the merged array nums1.
int p1 = m - 1;
int p2 = n - 1;
int p = m + n - 1;
// Iterate from the end of both arrays and place the larger element at the end of nums1.
while (p2 >= 0) {
// Check if there are still elements in nums1 to compare and if nums1's element is larger.
if (p1 >= 0 && nums1[p1] > nums2[p2]) {
nums1[p] = nums1[p1];
p1--;
} else {
// Otherwise, the element from nums2 is larger or nums1 is exhausted.
nums1[p] = nums2[p2];
p2--;
}
// Move to the next position to fill in nums1.
p--;
}
// If there are any elements left in nums1 (when n=0 or all of nums2 is smaller),
// they are already in their correct sorted positions, so no further action is needed.
}
}
Merge Sorted Array in C++
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
// Initialize p1 to the last valid element of nums1, and p2 to the last element of nums2.
int p1 = m - 1;
int p2 = n - 1;
// Initialize p to the last index of the merged array.
int p = m + n - 1;
// Merge in reverse order, from the end of the arrays.
while (p2 >= 0) {
// If p1 is valid and its element is greater than the element at p2.
if (p1 >= 0 && nums1[p1] > nums2[p2]) {
nums1[p] = nums1[p1];
p1--;
} else {
// Otherwise, take the element from nums2.
// This handles the case where p1 < 0 or nums2[p2] >= nums1[p1].
nums1[p] = nums2[p2];
p2--;
}
// Move to the next position in the merged array.
p--;
}
// If m > n, the remaining elements in nums1 are already in their correct sorted positions.
}
};
Merge Sorted Array in TypeScript
/**
Do not return anything, modify nums1 in-place instead.
*/
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
// Pointer for the last element of the initial part of nums1
let p1 = m - 1;
// Pointer for the last element of nums2
let p2 = n - 1;
// Pointer for the last position in the merged nums1 array
let p = m + n - 1;
// Merge nums1 and nums2 from the end, as long as there are elements in nums2.
while (p2 >= 0) {
// If p1 is in bounds and its element is larger than p2's element.
if (p1 >= 0 && nums1[p1] > nums2[p2]) {
// Place nums1's element at the end of the merged array.
nums1[p] = nums1[p1];
p1--;
} else {
// Place nums2's element at the end, either because it's larger
// or because all of nums1's initial elements have been processed.
nums1[p] = nums2[p2];
p2--;
}
// Move to the next position to fill.
p--;
}
// Any remaining elements at the start of nums1 are already in their correct sorted place.
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.