Algo-Sim › Two Pointers
Merge Sorted Array
Easy · Two Pointers · step through it in Java, Python and C++ on your own input
Merge nums2 into the spare tail of nums1 by filling from the back, so nothing unread is overwritten.
Problem
Two arrays nums1 and nums2 are sorted in non-decreasing order and hold m and n values. nums1 has length m + n: its last n slots are spare zeros. Merge nums2 into nums1 in place so that nums1 ends up sorted.
Constraints
- 0 ≤ m, n ≤ 200 and 1 ≤ m + n
- -10⁹ ≤ nums1[i], nums2[j] ≤ 10⁹
- Follow-up: O(m + n) time with no extra array
Edge cases to test
- n = 0 (nothing to merge)
- m = 0 (everything comes from nums2)
- Every nums2 value smaller than nums1’s
Follow-up questions
- Why fill from the back?
- The spare space is at the end of nums1, so writing the largest values there never overwrites an unread value: O(m + n), O(1) extra.
- What if you must merge k sorted arrays?
- A min-heap of the k current heads: O(N log k) for N values in total.
Solution
Java
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1, j = n - 1, w = m + n - 1;
while (j >= 0) {
if (i >= 0 && nums1[i] > nums2[j]) {
nums1[w--] = nums1[i--];
} else {
nums1[w--] = nums2[j--];
}
}
}Python
def merge(nums1, m, nums2, n):
i, j, w = m - 1, n - 1, m + n - 1
while j >= 0:
if i >= 0 and nums1[i] > nums2[j]:
nums1[w] = nums1[i]
i, w = i - 1, w - 1
else:
nums1[w] = nums2[j]
j, w = j - 1, w - 1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) {
int i = m - 1, j = n - 1, w = m + n - 1;
while (j >= 0) {
if (i >= 0 && nums1[i] > nums2[j]) {
nums1[w--] = nums1[i--];
} else {
nums1[w--] = nums2[j--];
}
}
}
};
More Two Pointers problems
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)