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 INPUT nums1 (length = m + n = 6) 1 2 3 0 0 0 m = 3 elements placeholders nums2 (length = n = 3) 2 5 6 Initial Pointers: p1 = m - 1 = 2 p2 = n - 1 = 2 p = m + n - 1 = 5 Input Values nums1=[1,2,3,0,0,0], m=3 nums2=[2,5,6], n=3 ALGORITHM STEPS 1 Start from End Fill nums1 from last position 2 Compare Elements Compare nums1[p1] vs nums2[p2] 3 Place Larger Value Put larger at nums1[p], decrement 4 Handle Remaining Copy leftover nums2 elements Merge Process (Backward) i=5: 6 > 3 --> [_,_,_,_,_,6] i=4: 5 > 3 --> [_,_,_,_,5,6] i=3: 3 > 2 --> [_,_,_,3,5,6] i=2: 2 = 2 --> [_,_,2,3,5,6] i=1: 2 > 1 --> [_,2,2,3,5,6] i=0: remain --> [1,2,2,3,5,6] Time: O(m+n) | Space: O(1) FINAL RESULT Merged nums1 Array: 1 2 2 3 5 6 0 1 2 3 4 5 OK - Sorted in Place! Output [1, 2, 2, 3, 5, 6] Properties: - In-place modification - Non-decreasing order - No extra space used - All elements merged - Length = 6 (m + n) Key Insight: By starting from the end of both arrays and filling nums1 backwards, we avoid overwriting elements that haven't been processed yet. This three-pointer technique achieves O(m+n) time with O(1) space, making it optimal for in-place merging of sorted arrays. TutorialsPoint - Merge Sorted Array | Optimal Three-Pointer Approach
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