8. Merge Sorted Array
easyAsked at YelpMerge nums2 into nums1 in-place — Yelp's analog for combining two sorted batches of incoming reviews into a single chronological feed without extra memory.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given two sorted integer arrays nums1 and nums2 of lengths m and n. nums1 has size m + n, with the last n slots set to 0 as padding. Merge nums2 into nums1 in-place in sorted order.
Constraints
nums1.length == m + nnums2.length == n0 <= m, n <= 200
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 = [1], m=1, nums2 = [], n=0[1]Approaches
1. Append + sort
Overwrite the tail and 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. Three pointers from the back
Fill from the tail using the larger of each cursor.
- 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:
Yelp-specific tips
Yelp rewards the backward three-pointer trick and follows up by asking how you'd merge new-review batches into the sorted business detail feed during a hot-path write.
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 Yelp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →