#88
Merge Sorted Array
EasyArrayTwo PointersSortingTwo PointersMerging Sorted Arrays
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m + n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(m + n)Space O(1)
The optimal approach uses a two-pointer technique to merge the arrays in-place, taking advantage of the fact that both arrays are already sorted. This avoids the need for extra space and sorting.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, one for nums1 (i = m - 1) and one for nums2 (j = n - 1), and a pointer for the end of nums1 (k = m + n - 1).
- 2Step 2: Compare the elements pointed to by i and j, and place the larger one at position k in nums1.
- 3Step 3: Move the pointer of the array from which the element was taken, and decrement k.
- 4Step 4: Repeat until all elements from nums2 are merged.
- 5Step 5: If any elements remain in nums2, copy them to nums1.
solution.py13 lines
1# Full working Python code
2
3def merge(nums1, m, nums2, n):
4 i, j, k = m - 1, n - 1, m + n - 1
5 while j >= 0:
6 if i >= 0 and nums1[i] > nums2[j]:
7 nums1[k] = nums1[i]
8 i -= 1
9 else:
10 nums1[k] = nums2[j]
11 j -= 1
12 k -= 1
13ℹ
Complexity note: The time complexity is O(m + n) because we traverse both arrays once. The space complexity is O(1) since we are merging in-place without using additional storage for the merged array.
- 1Both arrays are sorted, allowing for efficient merging without additional sorting.
- 2Using two pointers helps in optimizing the merging process by avoiding unnecessary comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.