This post is a Python solution to the Codility CyclicRotation problem (Lesson 2 – Arrays) which scored 100%. Now, Let’s understand the problem first.
CyclicRotation Problem:
Rotate an array to the right by a given number of steps.
Although the problem is described quite elaborately at Codility, here is just an outline with an example.
In this problem, there are 2 input parameters:
- A – an array consisting of N integers. Each element of array A is an integer within the range [−1,000..1,000].
- K – each element of A will be shifted to the right K times. K is an integer within the range [0..100];
The objective is to rotate array A K times; that is, each element of A will be shifted to the right K times.
Example:
A = [3, 8, 9, 7, 6]
K = 3
Expected Output: [9, 7, 6, 3, 8]
Python Solution:
If we check the above-expected output, although we are supposed to rotate the array 3 times like below, what we are actually doing is splitting the array at the Kth position and refitting it.
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
We will use K = K % n, where n is the total number of elements in the array. For this example, K = 3. Thus, we will return A[-3:] + A[:-3]
A = [3, 8, 9, 7, 6] A[-3:] + A[:-3]
Let’s take another example:
A = [1, 2, 3, 4] & K = 4
[1, 2, 3, 4] -> [4, 1, 2, 3]
[4, 1, 2, 3] -> [3, 4, 1, 2]
[3, 4, 1, 2] -> [2, 3, 4, 1]
[2, 3, 4, 1] -> [1, 2, 3, 4]
Now, for this example total elements in the array (n) = 4 and even K = 4. Thus, K = 4 % 4 = 0.
Now, splitting at position 0 which got the same output as the array.
Code:
Test Cases:
A = [3, 8, 9, 7, 6] K = 3 result = solution(A,K) print(result)
The function returned : [9, 7, 6, 3, 8]
A = [1, 2, 3, 4] K = 4 result = solution(A,K) print(result)
The function returned :[1, 2, 3, 4]
A = [0, 0, 0] K = 1
result = solution(A,K) print(result)
The Function returned: [0, 0, 0]
Conclusion:
Codility runs the solution for different test cases which are extremes and create a report with Test Results on Correctness and Performance. For this particular problem, Performance is not assessed.
For this problem, I have tried to write loops and rotate elements one by one and that works too. But the above solution looks most simple.
Please leave a comment if the solution did not work for you. Or, Clap once if you think the post is helpful.
Check for more solutions for codility problem:
Codility BinaryGap – Python Solution
Thank You!
7