Skip to main content

9. Merge Sorted Array

easyAsked at Wix

Merge two sorted arrays in-place; Wix uses this when merging a tenant's draft and published layout arrays before deploying a site.

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

Problem

You are given two sorted integer arrays nums1 and nums2, where nums1 has m+n length with the last n slots set to zero. Merge nums2 into nums1 as one sorted array, in-place.

Constraints

  • nums1.length == m + n
  • 0 <= m, n <= 200

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

Copy and sort.

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 end

Walk from the back so writes don't clobber reads.

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){
    nums1[k--]= (i>=0 && nums1[i]>nums2[j]) ? nums1[i--] : nums2[j--];
  }
}

Tradeoff:

Wix-specific tips

Wix likes a quick note on why writing from the tail prevents overwriting unread nums1 cells — they hit the same pattern in their delta-publish pipeline.

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 Wix interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →