DIY: Merge Sorted Arrays

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

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.

Input

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.

Output

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

{1,2,3,4,7,9}

Note: You have to modify nums1 in-place.

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