I am trying to modify the element nums1 after n so we create a loop that runs for n times . The elements in nums1 are modified are the mth element because nums1 lenght is m+n so we do not waste any iterations. After the elements are replaced they are sorted.
-
Time complexity: O((N+M)Log(N+M))
-
Space complexity: O(1)
/**
Do not return anything, modify nums1 in-place instead.
*/
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
let j = m
for (let i = 0; i < n; i++) {
nums1[j] = nums2[i]
j++
}
nums1.sort((a, b) => a - b)
};