Skip to main content

Command Palette

Search for a command to run...

Codility - CyclicRotation - JavaScript

Codility CyclicRotation problem solved in JavaScript

Updated
β€’2 min read
Codility - CyclicRotation - JavaScript
A
Systems Architect. Software Engineer. Full Stack Developer. Architect of Chaos, mastering cloud, legacy, and light.

πŸŒ€ 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, splice or temp variables.

  • Pure, declarative, loopless rotation.

  • Leverages slice() with negative indices (ES6+).

  • Handles large values of K gracefully (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/

Codility

Part 2 of 3

Codility problems solved in multiple programming languages.

Up next

Codility - BinaryGap - JavaScript

Codility BinaryGap problem solved in JavaScript