Merge two sorted arrays in place so that the first array contains the final sorted result.
You are given two integer arrays nums1 and nums2, both sorted in non-decreasing order. The first array nums1 has enough extra space at the end to hold all elements of nums2.
Merge the two arrays into nums1 so that the final array is also sorted in non-decreasing order. The merge should be done in place by updating nums1.
A common setup is that nums1 has length m + n, where the first m elements are valid and the remaining n positions are placeholders.
nums1: an integer array of length m + n, where the first m values are meaningful and the rest are empty slots.nums2: an integer array of length n.m: number of valid elements in nums1.n: number of elements in nums2.Both valid portions are sorted in non-decreasing order.
Modify nums1 in place so that its first m + n positions contain all elements from both arrays in sorted order.
0 <= m, n <= 200m + n == nums1.lengthnums1 and nums2 are sorted in non-decreasing ordernums1Example 1
Input
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output
[1,2,2,3,5,6]
Explanation
The two sorted arrays are combined into one sorted array, and the result is written back into nums1.
Example 2
Input
nums1 = [1], m = 1, nums2 = [], n = 0
Output
[1]
Explanation
There is nothing to merge from nums2, so nums1 remains unchanged.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.