Skip to main content

8. Merge Sorted Array

easyAsked at Unity

Merge two sorted arrays in place from the back. Unity uses this for asset-bundle splice patterns at load time.

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

Problem

Merge nums1 (length m + n) and nums2 (length n) into nums1 in-place. The first m elements of nums1 are the items to merge; the last n slots are zero-padded.

Constraints

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

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=[0], m=0, nums2=[1], n=1
Output
[1]

Approaches

1. Append + sort

Copy nums2 into the tail of nums1 and call 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-pointer from the back

Write largest values at the end so we never overwrite unmerged data.

Time
O(m+n)
Space
O(1)
function merge(a, m, b, n) {
  let i = m - 1, j = n - 1, k = m + n - 1;
  while (j >= 0) {
    if (i >= 0 && a[i] > b[j]) a[k--] = a[i--];
    else a[k--] = b[j--];
  }
}

Tradeoff:

Unity-specific tips

Unity wants the back-to-front merge because asset bundles must splice into preallocated slots without resizing during the loading frame.

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

Practice these live with InterviewChamp.AI →