Search⌘ K
AI Features

Merge Sorted Array

Explore how to merge two sorted integer arrays into one sorted array using the K-way merge pattern. Understand the problem constraints and practice implementing the solution to improve your coding interview skills.

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.

Go
usercode > main.go
package main
func mergeSorted(nums1 []int, m int, nums2 []int, n int) []int {
// Replace this placeholder return statement with your code
return make([]int, 0)
}
Merge Sorted Array