Skip to main content

9. Merge Sorted Array

easyAsked at GitHub

Merge two sorted integer arrays in place into nums1 — GitHub's setup for the three-way merge core: writing from the back to avoid clobbering unread input.

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

Problem

Given two sorted arrays nums1 and nums2 of lengths m and n, merge nums2 into nums1 in place to form one sorted array. nums1 has length m+n with the last n slots padded with zeros.

Constraints

  • nums1.length == m + n
  • nums2.length == 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. Brute force

Copy nums2 onto tail of nums1, then sort.

Time
O((n+m) log(n+m))
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 into the tail of nums1 — pointer i for nums1's real data, j for nums2, k for the write slot. Reverse merging avoids overwriting un-read input.

Time
O(n+m)
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:

GitHub-specific tips

GitHub uses this to verify you understand reverse merging — exactly the trick used to merge two sorted parent commit-date streams without a second buffer.

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

Practice these live with InterviewChamp.AI →