Codility - CyclicRotation - JavaScript
Codility CyclicRotation problem solved in JavaScript


π Cyclic Rotation β Explained Line by Line
The CyclicRotation problem asks to rotate an array to the right K times.
Each rotation moves the last element to the front.
Example:A = [3, 8, 9, 7, 6], K = 3 β Result: [9, 7, 6, 3, 8]
Here's the code:
function solution(A, K) {
if (A.length === 0) return [];
const N = K % A.length;
return [...A.slice(-N), ...A.slice(0, -N)];
}
π Code Breakdown
if (A.length === 0) return [];
Quick exit for empty arrays.
const N = K % A.length;
Normalize rotation count to avoid unnecessary cycles.
Handles cases where K exceeds array length by reducing full-circle rotations.
return [...A.slice(-N), ...A.slice(0, -N)];
Use slice() and spread to rearrange elements:
A.slice(-N)takes the last N elements (using negative offsets) βA.slice(-3)β[9, 7, 6]A.slice(0, -N)takes the remaining front βA.slice(0, -3)β[3, 8]Spread joins both into a rotated array (no mutation) β
[... [9, 7, 6], ... [3, 8]]
π§© Additional Notes
No
for,pop,shift,spliceortempvariables.Pure, declarative, loopless rotation.
Leverages
slice()with negative indices (ES6+).Handles large values of
Kgracefully (K % A.length).Minimalist, expressive, no loops, no mutations, runs with O(n) complexity.
π CyclicRotation from Lesson 2 β Arrays on Codility:
https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/





