Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Created March 4, 2026 18:50
Show Gist options
  • Select an option

  • Save Ephraimiyanda/3cd6be069b585c6258222ec79430af2f to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/3cd6be069b585c6258222ec79430af2f to your computer and use it in GitHub Desktop.
Merge Sorted Array

Question

Approach

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.

Complexity

  • Time complexity: O((N+M)Log(N+M))

  • Space complexity: O(1)

Code

/**
 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)
};
scrnli_6tb1rq5N9dLwi9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment