Merge Sorted Array
Updated
Problem 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 Onsite Interview questions
- Number of IslandsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Cheapest Flights Within K StopsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course SchedulePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course Schedule IIPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Dungeon GameONSITE INTERVIEW · Seen Nov 2026
- Integer BreakONSITE INTERVIEW · Seen Nov 2026
- LFU CacheONSITE INTERVIEW · Seen Nov 2026
- LRU Cache for Query ResultsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
- First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Merge Sorted ArrayDP World · ONSITE INTERVIEW
- Merge Two Arrays Into Sorted OrderNVIDIA · ONSITE INTERVIEWNVIDIA interview questions
- Two SumMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Squares of a Sorted ArrayBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Assign CookiesExpedia · PHONE SCREEN · ONSITE INTERVIEWExpedia interview questions
- Combine Two Sorted Lists Into OneDocuSign · ONSITE INTERVIEWDocuSign interview questions
- 3Sum SmallerSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Sort Ones, Twos, and Threes In PlaceAgoda · PHONE SCREEN · ONSITE INTERVIEWAgoda interview questions
- Minimum Station Tracks for a Train ScheduleBNSF Railway · ONSITE INTERVIEWBNSF Railway interview questions
- Count Triplets With Sum at Most TargetGoogle · ONSITE INTERVIEWGoogle interview questions