Skip to main content

Merge Sorted Array

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums2 into nums1 in non-decreasing order.

Problems51 / 152
Sign in

Merge Sorted Array

EASYArrayTwo Pointers

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums2 into nums1 in non-decreasing order.

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]
Show hint

Start from the end of both arrays. Compare elements and place larger ones at the end of nums1, working backwards.

Draft saves automatically

Loading editor...

Submit also runs hidden tests
nums1 =
[1,2,3,0,0,0]
m =
3
nums2 =
[2,5,6]
n =
3
Expected
[1,2,2,3,5,6]
Run with your own input (JSON)