PIXELBANKv8.2.1
Menu

Merge Sorted Array

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).

Output the merged array as space-separated integers.

Example:

Input:
1,2,3,0,0,0
3
2,5,6
3
Output:
1 2 2 3 5 6
Reasoning:
  • The input array nums1 is [1, 2, 3, 0, 0, 0] with m = 3 valid elements, and nums2 is [2, 5, 6] with n = 3 elements.
  • We merge nums2 into nums1 in-place, starting from the end of both arrays, comparing elements and placing the larger one at the end of nums1.
  • The merge process involves iterating through both arrays, resulting in the following steps:
    • Comparing 3 from nums1 and 6 from nums2, placing 6 at the end of nums1.
    • Comparing 2 from nums1 and 5 from nums2, placing 5 at the second last position of nums1.
    • Comparing 2 from nums1 and 2 from nums2, placing 2 at the third last position of nums1, and the remaining 2 from nums1 is placed before it.
  • The final output is the merged and sorted array [1, 2, 2, 3, 5, 6].

Constraints:

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

Test Results

0/0
Run code to see test results.