Skip to main content

8. Merge Sorted Array

easyAsked at Dropbox

Merge two sorted arrays in place into the first; Dropbox uses it as a stand-in for merging local-edit and server-edit sequences during reconciliation.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given nums1 of size m+n with the first m elements sorted and trailing n zero slots, and nums2 of size n sorted, merge nums2 into nums1 in place so nums1 ends sorted.

Constraints

  • 0 <= m, n <= 200
  • nums1.length == m + n
  • Both inputs are sorted ascending

Examples

Example 1

Input
nums1=[1,2,3,0,0,0], m=3, nums2=[2,5,6], n=3
Output
[1,2,2,3,5,6]

Example 2

Input
nums1=[1], m=1, nums2=[], n=0
Output
[1]

Approaches

1. Concat + sort

Overwrite trailing slots, 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. Three-pointer from the back

Write the larger of nums1[i], nums2[j] at index k=m+n-1 and decrement. Avoids any shifting.

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:

Dropbox-specific tips

Dropbox interviewers expect 'fill from the back' to come out unprompted — walking forward forces shifts, which they map to wasteful O(n) buffer copies in the sync engine.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Merge Sorted Array and other Dropbox interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →