Merge Sorted Array - Problem

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

Input & Output

Example 1 — Basic Merge
$ Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
💡 Note: Merge [1,2,3] and [2,5,6] into sorted order. The final merged array is [1,2,2,3,5,6] stored in nums1.
Example 2 — One Empty Array
$ Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
💡 Note: nums2 is empty, so nums1 remains [1] unchanged.
Example 3 — First Array Empty
$ Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
💡 Note: nums1 has no actual elements (m=0), so the result is just nums2 = [1].

Constraints

  • nums1.length == m + n
  • nums2.length == n
  • 0 ≤ m, n ≤ 200
  • 1 ≤ m + n ≤ 200
  • -109 ≤ nums1[i], nums2[i] ≤ 109

Visualization

Tap to expand
Merge Sorted Array ProblemInput:nums1: [1,2,3,0,0,0] m=3123000nums2: [2,5,6] n=3256↓ Merge Process ↓Compare elements and merge in sorted orderOutput:nums1: [1,2,2,3,5,6]122356Merged and sorted in-place!
Understanding the Visualization
1
Input
Two sorted arrays with nums1 having extra space
2
Process
Merge elements maintaining sorted order
3
Output
Single sorted array stored in nums1
Key Takeaway
🎯 Key Insight: Merge backwards to avoid overwriting elements while leveraging sorted property
Asked in
Microsoft 85 Facebook 72 Amazon 68 Apple 45 Google 38
892.0K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen