#88EasyTwo Pointers

Merge Sorted Array

Merge two sorted arrays in-place by filling from the back.

MicrosoftAmazonGoogleBloombergAdobe

Problem Statement

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n. Merge nums2 into nums1 in-place. nums1 has a length of m + n, where the last n elements are 0 (placeholders).

Examples

Example 1

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

Example 2

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

Constraints

  • nums1.length == m + n
  • 0 ≤ m, n ≤ 200
  • 1 ≤ m + n ≤ 200
  • -10⁹ ≤ nums1[i], nums2[j] ≤ 10⁹

Solutions

1
Copy and Sort
TimeO((m+n) log(m+n))SpaceO(1)

Copy nums2 elements into nums1 after the first m elements, then sort. Simple but doesn't use the sorted property.

Visual Animation
def merge(nums1, m, nums2, n) -> None:
    nums1[m:] = nums2
    nums1.sort()

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Two Pointers to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems