InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Merge Sorted Array

easy Original ↗ 00:00

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 = 3nums1 = [1,2,2,3,5,6] The three real values of each array interleave into one sorted run.
  • nums1 = [1], m = 1, nums2 = [], n = 0nums1 = [1] Nothing to merge; nums1 is already the answer.
  • nums1 = [0], m = 0, nums2 = [1], n = 1nums1 = [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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug