Skip to main content
Back to problems
Leetcode
Easy
Arrays
Sorting
Two Pointers
Amazon
Microsoft
Merge Sorted Array

Merge two sorted arrays in place so that the first array contains the final sorted result.

Acceptance 83%
Problem Statement

You are given two integer arrays nums1 and nums2, both sorted in non-decreasing order. The first array nums1 has enough extra space at the end to hold all elements of nums2.

Merge the two arrays into nums1 so that the final array is also sorted in non-decreasing order. The merge should be done in place by updating nums1.

A common setup is that nums1 has length m + n, where the first m elements are valid and the remaining n positions are placeholders.

Input Format

  • nums1: an integer array of length m + n, where the first m values are meaningful and the rest are empty slots.
  • nums2: an integer array of length n.
  • m: number of valid elements in nums1.
  • n: number of elements in nums2.

Both valid portions are sorted in non-decreasing order.

Output Format

Modify nums1 in place so that its first m + n positions contain all elements from both arrays in sorted order.

Constraints

  • 0 <= m, n <= 200
  • m + n == nums1.length
  • nums1 and nums2 are sorted in non-decreasing order
  • The merge should use the existing storage in nums1
Examples
Sample cases returned by the problem API.

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]

Explanation

The two sorted arrays are combined into one sorted array, and the result is written back into nums1.

Example 2

Input

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

Output

[1]

Explanation

There is nothing to merge from nums2, so nums1 remains unchanged.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.