Search⌘ K
AI Features

Merge Sorted Array

Explore how to merge two sorted arrays into a single sorted array using an in-place approach in C++. Learn to manage array length constraints and combine elements efficiently. This lesson helps you solve common array merging problems seen in coding interviews.

Statement

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

Your task is to merge the elements of nums2 into nums1 so that nums1 becomes a single array sorted in non-decreasing order.

The merged result is stored in nums1, which has a total length of m + n. The first m positions contain the initial elements, the last n positions are placeholders (initialized to 0), and nums2 contains the n elements to merge.

Constraints:

  • nums1.length =m+n= m + n
  • nums2.length =n= n
  • 0m,n2000 \leq m, n \leq 200
  • 1m+n2001 \leq m + n \leq 200
  • 103-10^3 \leq nums1[i], nums2[j] 103\leq 10^3

Examples

canvasAnimation-image
1 / 8

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Merge Sorted Array

1.

What is the output if the following arrays and values of mm and nn are given as input?

nums1 = [1, 2, 7, 92, 0, 0, 0], m = 4

nums2 = [3, 4, 5], n = 3

A.

[1, 2, 3, 4, 5, 7, 92]

B.

[1, 2, 7, 92, 3, 4, 5]

C.

[3, 4, 5, 1, 2, 7, 92]


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

C++
usercode > main.cpp
vector<int> mergeSortedArray(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
// Replace this placeholder return statement with your code
return {};
}
Merge Sorted Array