Rotate array by K steps

Simplify Rotation Amount

For an array of sized nn instead of doing  K K rotation

K=n+n+n+...+x K = n + n + n + ... + x 

we can simply do K%nK\%n rotation

x=K%nx = K\%n

If we rotate KKsteps to right we need to start reading the rotated array from the last K%nK\%nelements.

If we rotate KKsteps to left we need to start reading the rotated array after skipping K%nK\%nelements from start

Rotation

Complexity

  • Time complexity : O(n)\text{O}(n)

    • We iterate the whole array only once

  • Space complexity : O(1)\text{O}(1)

    • No extra space is needed

Code

Last updated