Merge Two Sorted Arrays

EasyArrayBinary SearchSorting

Description

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should be returned by the function. Return the result as an array.

Examples

Input:nums1 = [1,2,3], nums2 = [2,5,6]
Output:[1,2,2,3,5,6]
Explanation:

Two-pointer merge: compare 1 vs 2 → take 1. Compare 2 vs 2 → take 2. Compare 3 vs 2 → take 2. Compare 3 vs 5 → take 3. Take remaining 5, 6. Result: [1,2,2,3,5,6].

Input:nums1 = [1], nums2 = []
Output:[1]
Explanation:

When merging a non-empty array [1] with an empty array [], the result is simply [1] since there are no elements to interleave.

Input:nums1 = [], nums2 = [1]
Output:[1]
Explanation:

Nums1 is empty [], so there are no elements to compare. Simply return all elements from nums2: [1].

Input:nums1 = [1,3,5], nums2 = [2,4,6]
Output:[1,2,3,4,5,6]
Explanation:

Two-pointer merge: 1<2 → take 1. 3>2 → take 2. 3<4 → take 3. 5>4 → take 4. 5<6 → take 5. Take 6. Result: [1,2,3,4,5,6].

Constraints

  • 0 ≤ nums1.length, nums2.length ≤ 200
  • -10⁹ ≤ nums1[i], nums2[j] ≤ 10⁹

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!