Good morning! Here's our prompt for today.
Merge Sorted Arrays
Let's tackle a problem where we need to merge two sorted arrays into one larger sorted array.
Problem Statement
We are given two integer arrays, nums1
and nums2
, that are both sorted in non-decreasing order.
We are also given the number of elements in each array, m
and n
.
Our goal is to:
- Merge the two arrays into a single array
- Ensure the merged array is also sorted
The catch is that instead of creating a new array, we need to do the merge in-place into nums1
.
nums1
has extra space at the end to fit all the elements. We should:
- Merge
nums2
into the end ofnums1
- Sort the final result in
nums1
Example
1nums1 = [1, 2, 3, _, _, _], m = 3
2nums2 = [2, 5, 6], n = 3
3
4Result: nums1 = [1, 2, 2, 3, 5, 6]
We merged the sorted arrays [1, 2, 3] and [2, 5, 6] into the sorted result [1, 2, 2, 3, 5, 6].

Constraints
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
-109 <= nums1[i], nums2[j] <= 109
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
var assert = require('assert');
​
var merge = function(nums1, m, nums2, n) {
// Enter your code here
return nums1;
};
​
try {
assert.deepEqual(
merge([1,2,3], 3, [2,5,6], 3), [1,2,2,3,5,6]
);
​
console.log(
'PASSED: ' +
"merge([1,2,3], 3, [2,5,6], 3) should return '[1,2,2,3,5,6]'"
);
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(merge([1,10,55,66], 4, [21,48,68,80], 4), [1,10,21,48,55,66,68,80]);
​
console.log(
'PASSED: ' + "merge([1,10,55,66], 4, [21,48,68,80], 4) should return '[1,10,21,48,55,66,68,80]'"
);
} catch (err) {
console.log(err);
}
We'll now take you through what you need to know.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.