Merge Sorted Array
2 approaches, code in every language
Problem description
Two integer arrays are given in non-decreasing order. The first array has spare room at its tail sized to hold the second array's contents: its real length is m, followed by n zero placeholders, while the second array has length n.
Merge the two so the first array ends up holding all m + n values in non-decreasing order, and do the work in place rather than returning a new array.
Example 1
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
The placeholder zeros in nums1 get overwritten by the merged order.
Example 2
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Constraints
nums1.length == m + n0 ≤ m, n ≤ 200-10^9 ≤ nums1[i], nums2[j] ≤ 10^9
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Merge Into the Padded Log is our own problem on the technique behind Merge Sorted Array: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free