8. Merge Sorted Array
easyAsked at SpotifyMerge nums2 into nums1 in place where nums1 has space at the end.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given two sorted integer arrays nums1 (size m+n with last n slots empty) and nums2 (size n), merge nums2 into nums1 as one sorted array in place.
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. Concat + sort
Copy nums2 into nums1 tail then sort the whole thing
- 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. Reverse two pointers
Fill from the back: largest remaining of m or n goes into the tail slot. Avoids overwriting unread data.
- 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:
Spotify-specific tips
Spotify's playlist-merge service relies on this exact reverse-pointer technique when combining personalized and editorial picks without allocating an extra buffer per request.
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 Spotify interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →