Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Last active February 4, 2026 23:45
Show Gist options
  • Select an option

  • Save Ephraimiyanda/8b8fcba3532b82e85cbae887201b472b to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/8b8fcba3532b82e85cbae887201b472b to your computer and use it in GitHub Desktop.
Rotate Array

Question

Approach

I created a copy of the array to be able to track the rotation of the array by k numbers.

I first thought of this

function rotate(nums: number[], k: number): void {
    let n = nums.length
    let copy = [...nums];
    for (let i = 0; i < n; i++) {
        if (i + k >= n) {
           nums[i + k - n] = copy[i] 
        }else{
            nums[i + k] = copy[i] 
        }
    };
};

but then it led to repeating values for arrays with lengths of 1 and also i + k -n can still be greater than n after the subtraction. so instead i use the mod operator% to get the index to be rotated to

Complexity

  • Time complexity:O(N)

  • Space complexity:O(N)

Code

/**
 Do not return anything, modify nums in-place instead.
 */
function rotate(nums: number[], k: number): void {
    let n = nums.length
    let copy = [...nums];
    for (let i = 0; i < n; i++) {
        nums[(i + k) % n] = copy[i]


    };
};
scrnli_hOdYEP5RqnR0Pl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment