DIY: Merge Sorted Arrays

Solve the interview question "Merge Sorted Arrays" in this lesson.

We'll cover the following

Problem statement

Let’s say you are given two sorted integer arrays, nums1 and nums2. You are also given the number of elements initialized in both of the arrays, which are m and n, respectively. Implement a function that merges the second array into the first one.

Note: Assume that nums1 has a size equal to m + n, meaning it has enough space to hold additional elements from nums2.


The inputs will be two integer arrays and two integers representing the number of initialized elements in both of the arrays. For example, consider the following inputs:

nums1 = [3,4,9,0,0,0]
m = 3
nums2 = [1,2,7]
n = 3

The zeroes at the end of nums1 represent uninitialized integers. This additional space will be used to merge it with nums2.


The function will return the nums1 array after nums2 has been merged with it. The following is the output for the inputs mentioned above:


Note: You have to modify nums1 in-place.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.

Learn to code, grow your skills, and succeed in your tech interview