How to rotate an array to the right by K steps
Given an array of integers
and k
, return a rotated array
to the right by k
steps
Example 1
Input: array = [1, 2, 3, 4], k = 1
Output: [4, 1, 2, 3]
Example 2
Input: array = [1, 2, 3, 4], k = 0
Output: [1, 2, 3, 4]
Algorithm
First of all, we need to answer the question. What does it meat to rotate an array to the right n k
steps?
To rotate an array on
k
steps we need to move each element onk
steps to the right other words each element's index should be incremented onk
.
Let's see an example step by step
k
is equal to two
, each element's index should be incremented by two. It can be done by two steps, on each step, an index
will be incremented by one
.
It's easy for indexes: 0, 1, 2
. What should we do for 3, 4, and 5
? After incremented by 2
an index will be out of the array bounds. To solve it we can use the euclidean division and count a new index by formula:
(i + k) % array.Length
. wherei
is an element's index in the array
Calculation of a new index:
(0 + 2) % 5 = 2
(1 + 2) % 5 = 3
(2 + 2) % 5 = 4
(3 + 2) % 5 = 0
(4 + 2) % 5 = 1
Code
public int[] Rotate(int[] array, int k)
{
if (array == null || array.Length == 0 || k == 0)
{
return array;
}
var result = new int[array.Length];
for (int i = 0; i < array.Length; i++)
{
result[(i + k) % array.Length] = array[i];
}
return result;
}
Time Complexity: O(n)