Skip to content
Decoder

Merge Sorted Array

Easy

Problem

You are given two lists sorted in non-decreasing order, nums1 and nums2, and two counts m and n. The first m values of nums1 are real; its last n slots are placeholders (zeros) with room for nums2. nums2 holds exactly n values.

Merge nums2 into nums1 in place so that nums1 becomes one sorted list of length m + n. Do not return anything.

Example 1

Input
nums1 = [1, 2, 3, 0, 0, 0], m = 3, nums2 = [2, 5, 6], n = 3
Output
nums1 becomes [1, 2, 2, 3, 5, 6]

Example 2

Input
nums1 = [1], m = 1, nums2 = [], n = 0
Output
nums1 stays [1]

Example 3

Input
nums1 = [0], m = 0, nums2 = [1], n = 1
Output
nums1 becomes [1]

Constraints

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200 and 1 <= m + n <= 200
  • -10^9 <= nums1[i], nums2[j] <= 10^9
  • Aim for O(m + n) time.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.