Codility - CyclicRotation

A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.

For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.

Write a function that, given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times.

For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8].

Assume that:

  • N and K are integers within the range [0..100];
  • each element of array A is an integer within the range [−1,000..1,000].

In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.

function solution(A, K) {

    var size = A.length;
    var ret = [];

    if (K < 0 || K > 100 || size == 0) {
        return ret;
    }

    if (size == 1) {
        return A;
    }

    for (i = 0; i < size; i++) {
        ret[(i + K) % size] = A[i];
    }

    return ret;
}

Some of the steps are obvious but let’s see the rest of them.

If we want to shift an element K times we can calculate the new index by using (index + shift_times) % size_of_element, but how does this actually work.

The modulo operator returns the reminder of the division between two numbers. So if we have an array with 10 elements, and we want to shift the index 3, 5 times if we do it manually we can figure out that the new index should be 8.

3 + 5 = 8
8 % 10 = 8

But lets say that the array has 5 elements instead of 10 then, we know that we need to shift the array to position 3, if you do it one step at a time you can verify that it’s so.

3 + 5 = 8
8 % 5 = 3

But what if the array had 3 elements

3 + 5 = 8
8 % 3 = 2

And there you go very simple.