InterviewPrepKit

Home / Coding / Two Pointers

Merge Sorted Array

easy Original β†—
Solving tips
  • The free space is at the END of nums1, so merge backward: three pointers writing the larger of nums1[i]/nums2[j] into index m+n-1 downward.
  • Merging forward overwrites unread nums1 values; going backward keeps the write pointer ahead of both reads so nothing is clobbered.
  • Loop while j >= 0 (leftover nums1 prefix is already in place); guard i >= 0 in the comparison since Python nums1[-1] silently wraps.
  • O(m+n) time, O(1) space (meets the follow-up); mutate nums1 in place rather than returning a new list.

Problem

You are given two integer arrays that are each already sorted in non-decreasing order: nums1 of length m + n and nums2 of length n. Only the first m slots of nums1 hold real values β€” the trailing n slots are filler zeros reserved as extra space.

Merge nums2 into nums1 so that nums1 ends up as one sorted array of all m + n values. Do the merge in place: do not return anything and do not allocate a new array for the answer (the graders inspect nums1 directly).

Examples

  • nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 β†’ nums1 = [1,2,2,3,5,6] The three real values of each array interleave into one sorted run.
  • nums1 = [1], m = 1, nums2 = [], n = 0 β†’ nums1 = [1] Nothing to merge; nums1 is already the answer.
  • nums1 = [0], m = 0, nums2 = [1], n = 1 β†’ nums1 = [1] nums1 has no real values, so the result is just nums2 copied in.

Constraints

  • 0 <= m, n <= 200, 1 <= m + n <= 200
  • -10^9 <= nums1[i], nums2[i] <= 10^9
  • Follow-up: do it in O(m + n) time with O(1) extra space.

Think about it first

Hint 1 Both inputs are already sorted. Sorting the combined array from scratch throws that information away β€” a merge should never need to compare more than each element once.
Hint 2 If you merge front-to-back inside `nums1`, you overwrite values of `nums1` you haven't consumed yet. Where in `nums1` is there guaranteed free space?
Hint 3 The free space is at the **end**. Walk pointers backward from `nums1[m-1]` and `nums2[n-1]`, writing the larger of the two into position `m + n - 1`, then `m + n - 2`, and so on. Nothing unconsumed is ever overwritten.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.