12 · Two Pointers

#88 Merge Sorted Array

Easysolve on LeetCode ↗

frequently reported atMetaBloombergMicrosoftGoogleAmazonTCS

the problem

In plain words

nums1 has room for m + n numbers: its first m values are sorted and its last n slots are free (they hold 0). nums2 holds n sorted numbers. Merge nums2 into nums1 so that all m + n numbers end up sorted in nums1. Return nothing.

in nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

out [1,2,2,3,5,6]

in nums1 = [1], m = 1, nums2 = [], n = 0

out [1]

in nums1 = [0], m = 0, nums2 = [1], n = 1

out [1]

m = 0, so the 0 in nums1 is only a free slot.

  • 0 ≤ m, n ≤ 200
  • 1 ≤ m + n ≤ 200
  • -10⁹ ≤ values ≤ 10⁹
  • Follow-up: O(m + n) time

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #21
      Merge Two Sorted Lists
      Easyin Linked Lists
    2. #977
      Squares of a Sorted Array
      Easyin Two Pointers
    3. #23
    4. #4
      Median of Two Sorted Arrays
      Hardin Binary Search