Problem · Array

Merge Sorted Array

Learn this problem
EasyAmazonNEW GRADONSITE INTERVIEW
See Amazon hiring insights

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.

  • nums1 has length m + n. Its first m elements are valid input values, while its final n positions are placeholders that should be ignored before the merge.
  • nums2 has length n.

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 + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -10^9 <= nums1[i], nums2[j] <= 10^9
  • The first m elements of nums1 and all elements of nums2 are sorted in non-decreasing order.

More Amazon problems

drafts saved locally
public int[] mergeSortedArray(int[] nums1, int m, int[] nums2, int n) {
  // write your code here
}
nums1[1,2,3,0,0,0]
m3
nums2[2,5,6]
n3
expected[1,2,2,3,5,6]
checking account