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

public void rotate(int[] nums, int k) { 
	k %= nums.length; 
	reverse(nums, 0, nums.length - 1); 
	reverse(nums, 0, k - 1); 
	reverse(nums, k, nums.length - 1); 
}

public void reverse(int[] nums, int start, int end) { 
	while (start < end) { 
		int temp = nums[start]; 
		nums[start] = nums[end]; 
		nums[end] = temp; 
		start++; 
		end--; 
	} 
}

Last updated