9. Merge Sorted Array
easyAsked at CourseraMerge two sorted arrays in-place — Coursera tests back-fill two-pointer technique for in-place enrollment merges.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given nums1 of length m+n with m valid elements then n zeros, and nums2 of length n, merge nums2 into nums1 in-place so nums1 becomes a sorted union.
Constraints
0 <= m, n <= 2001 <= m + n <= 200nums1.length == m + n
Examples
Example 1
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3[1,2,2,3,5,6]Example 2
nums1 = [0], m = 0, nums2 = [1], n = 1[1]Approaches
1. Concat + sort
Drop nums2 into the zeros, sort the whole array.
- Time
- O((m+n) log(m+n))
- Space
- O(1)
for (let i = 0; i < n; i++) nums1[m + i] = nums2[i];
nums1.sort((a,b) => a-b);Tradeoff:
2. Back-fill two pointers
Walk from the tail; place the larger value at index m+n-1.
- Time
- O(m+n)
- Space
- O(1)
function merge(nums1, m, nums2, n) {
let i = m - 1, j = n - 1, k = m + n - 1;
while (j >= 0) {
if (i >= 0 && nums1[i] > nums2[j]) nums1[k--] = nums1[i--];
else nums1[k--] = nums2[j--];
}
}Tradeoff:
Coursera-specific tips
Coursera reviewers will probe whether you can keep the merge O(1) extra memory — they batch-merge enrollment shards in services that can't afford an allocation per merge.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Merge Sorted Array and other Coursera interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →