v9.1.1
Menu

Merge Sorted Array

easyPROArrays & StringsMeta DSA

You are given two sorted integer arrays nums1 and nums2, and integers m and n representing the number of elements in each.

Merge nums2 into nums1 in-place so that nums1 is sorted. nums1 has length m + n with the last n elements set to 0 (placeholders).

The function returns nothing: it only modifies nums1. The tests then print the merged nums1 as space-separated integers, so do not print inside the function.

Example

Input
1,2,3,0,0,0
3
2,5,6
3
Output
1 2 2 3 5 6
Reasoning
  • Inputs: nums1 =[1,2,3,0,0,0]= [1, 2, 3, 0, 0, 0] has length m+n=6m + n = 6, but only its first m=3m = 3 entries (1,2,31, 2, 3) are real values. The three trailing zeros are empty slots, not data. nums2 =[2,5,6]= [2, 5, 6] holds the other n=3n = 3 values.
  • Math: take all six values, 1,2,31, 2, 3 and 2,5,62, 5, 6, and arrange them in non-decreasing order: 1≤2≤2≤3≤5≤61 \le 2 \le 2 \le 3 \le 5 \le 6. The value 22 is in both inputs, so it appears twice.
  • Output: 1 2 2 3 5 6, exactly m+n=6m + n = 6 numbers, held in the same nums1 list that was passed in, overwriting the placeholder slots. No zero survives because none of the zeros was a real value.
  • Notice the edge cases: with m=0m = 0 every slot of nums1 is a placeholder and the answer is just nums2; with n=0n = 0 nums1 is already the answer.

Constraints

  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -10^9 <= nums1[i], nums2[i] <= 10^9

Learn this in

More from Meta DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.