Merge Sorted Array
Easy · Two Pointers · Array · Two Pointers · Sorting
Problem
nums1 has length m + n: its first m entries are sorted values and the remaining n are zero padding. nums2 holds n sorted values.
Merge them into nums1 in place, keeping it sorted.
Examples
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1]
Nothing to merge.
Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [1]
nums1 contributes nothing.
Constraints
- len(nums1) == m + n
- len(nums2) == n
- 0 <= m, n <= 200
- -10^9 <= values <= 10^9
Approaches
- Overwrite the tail and sort — time O((m+n) log(m+n)), space O(1)*
Related problems
Start free on Cariara · Coding problems · System design studio