Menu
CoddyTech

Merge Sorted Array

You get two arrays of integers, nums1 and nums2. Each one is already sorted in non-decreasing order. Return a single array that holds every value from both, also in non-decreasing order. A value that appears in both arrays appears in the result as many times as it appears in total.

Function

merge(nums1: integer-array, nums2: integer-array) → integer-array
nums1integer-array
the first sorted array
nums2integer-array
the second sorted array
Returnsinteger-array
all values of both arrays in one sorted array, of length nums1.length + nums2.length

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 2000
  • -105 ≤ nums1[i], nums2[j] ≤ 105
  • nums1 and nums2 are each sorted in non-decreasing order.

Examples

Input
nums1 = [1, 4, 9]nums2 = [2, 3, 10]
Output
[1, 2, 3, 4, 9, 10]
Explanation
Read the two fronts and keep the smaller: 1, then 2 and 3 from nums2, then 4 and 9 from nums1, and 10 last. The result holds all six values.

lock icon+13 hidden tests on Submit

challenge icon

Follow-up

Can you merge k sorted arrays, holding N values in total, in O(N log k) time?

Reset code
def merge(nums1, nums2):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums1 = [1, 4, 9]
nums2 = [2, 3, 10]

Expected

[1, 2, 3, 4, 9, 10]