88. Merge Sorted Array
Asked at 34Meta87Bloomberg73Microsoft72Google69Amazon67Apple57EPAM Systems80tcs73Yandex63Squarespace100Avito83Hubspot80HCL76Zoho70Swiggy69persistent systems69AMD69Palo Alto Networks65Wipro63Verkada60Qualcomm58Cognizant57Nvidia55Morgan Stanley54Accenture54Samsung53Cisco45Infosys39Visa39DE Shaw38IBM35Goldman Sachs33TikTok26LinkedIn20
Problem
nums1 has length m + n: its first m values are sorted and the last n slots are zeros. Merge the sorted array nums2 (length n) into nums1 in place so that all m + n values end up sorted.
Example: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 → nums1 = [1,2,2,3,5,6]
Constraints: follow-up: O(m + n) time.
Fill nums1 from the back: the largest remaining element goes to position k. Working backwards never overwrites unread data.
Complexity: O(m + n) time, O(1) space.
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
i, j, k = m - 1, n - 1, m + n - 1
while j >= 0:
if i >= 0 and nums1[i] > nums2[j]:
nums1[k] = nums1[i]; i -= 1
else:
nums1[k] = nums2[j]; j -= 1
k -= 1
a = [1, 2, 3, 0, 0, 0]; Solution().merge(a, 3, [2, 5, 6], 3)
assert a == [1, 2, 2, 3, 5, 6]
b = [0]; Solution().merge(b, 0, [1], 1)
assert b == [1]
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1, j = n - 1, k = m + n - 1;
while (j >= 0) {
if (i >= 0 && nums1[i] > nums2[j]) nums1[k--] = nums1[i--];
else nums1[k--] = nums2[j--];
}
}
}
func merge(nums1 []int, m int, nums2 []int, n int) {
i, j, k := m-1, n-1, m+n-1 // fill from the back
for j >= 0 {
if i >= 0 && nums1[i] > nums2[j] {
nums1[k] = nums1[i]
i--
} else {
nums1[k] = nums2[j]
j--
}
k--
}
}