Problem · Array
Merge Sorted Array
Learn this problemProblem statement
You are given two integer arrays nums1 and nums2, each sorted in non-decreasing order, and two integers m and n representing the number of valid elements in the arrays.
Merge the valid elements of nums1 and all elements of nums2 into nums1 in non-decreasing order.
nums1has lengthm + n. Its firstmelements are valid input values, while its finalnpositions are placeholders that should be ignored before the merge.nums2has lengthn.
Modify nums1 in place, then return the merged nums1.
Function
mergeSortedArray(nums1: int[], m: int, nums2: int[], n: int) → int[]Examples
Example 1
nums1 = [1,2,3,0,0,0]m = 3nums2 = [2,5,6]n = 3return = [1,2,2,3,5,6]The valid portions are [1,2,3] and [2,5,6]. Their merged order is [1,2,2,3,5,6].
Example 2
nums1 = [1]m = 1nums2 = []n = 0return = [1]The second array is empty, so nums1 remains unchanged.
Example 3
nums1 = [0]m = 0nums2 = [1]n = 1return = [1]nums1 has no valid input elements. Its single position is merge capacity for the value from nums2.
Constraints
nums1.length == m + nnums2.length == n0 <= m, n <= 2001 <= m + n <= 200-10^9 <= nums1[i], nums2[j] <= 10^9- The first
melements ofnums1and all elements ofnums2are sorted in non-decreasing order.
More Amazon problems
- Resolve Task DependenciesONSITE INTERVIEW · Seen Jul 2026
- Shortest Distance on a Circular Bus RouteOA · Seen Jul 2026
- Longest Increasing Subsequence With Bounded Adjacent DifferenceONSITE INTERVIEW · Seen Jul 2026
- Search in a Rotated Sorted ArrayONSITE INTERVIEW · Seen Jul 2026
- Sliding Window MaximumONSITE INTERVIEW · Seen Jul 2026
- Merge IntervalsOA · Seen Jul 2026
- Sort Bug Report FrequenciesOA · Seen Jul 2026
- Drone Delivery RouteOA · Seen Jul 2026