Merge Sorted Array In Place

EasyTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given two integer arrays nums1 and nums2, each already sorted in **non-decreasing** order. You are also given two integers m and n, where m is the number of meaningful elements in nums1 and n is the number of elements in nums2. The array nums1 has a total length of m + n. Its first m slots hold the elements to merge, while the final n slots are zero placeholders that exist solely to leave room for the result. Merge the elements of nums2 into nums1 so that nums1 becomes a single array sorted in non-decreasing order. The merge must happen **in place** inside nums1 — do not allocate a separate result array. Return the merged nums1. A natural way to avoid overwriting values you still need is to fill nums1 from the back, comparing the largest remaining elements of each array and placing them at the highest unused index.

Examples

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
The values to merge are [1,2,3] from nums1 and [2,5,6] from nums2. Combined and sorted they form [1,2,2,3,5,6], which now fills all six slots of nums1.
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
nums2 is empty, so nums1 already holds the final sorted sequence and is unchanged.
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
nums1 contributes no real elements (m = 0); its single slot is a placeholder filled by the only element of nums2.

Constraints

  • `nums1.length == m + n`
  • `nums2.length == n`
  • `0 <= m, n <= 1000`
  • `1 <= m + n <= 2000`
  • `-10^9 <= nums1[i], nums2[i] <= 10^9`
  • The first `m` elements of `nums1` and all of `nums2` are sorted in non-decreasing order; the last `n` elements of `nums1` are `0` placeholders.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems