Rotate an array left by k steps in JavaScript
Intermediate · 4 min read
Rotating a list means sliding every item along and wrapping the ones that fall off one end round to the other. Rotate [1, 2, 3, 4, 5] left by 2 and you get [3, 4, 5, 1, 2]. Carousels, turn order in a game, a weekly rota and "show the next five" all work this way.
In this tutorial you will write rotate(xs, k). It must work when k is bigger than the list and when k is negative. The rotation itself takes one line. Getting the number of steps right takes most of the work, and that is what this lesson is really about. You should know arrays, slice and spread (...).
The % operator
% gives the remainder after dividing. It is how you make a number "wrap round".
console.log(7 % 5); // 2: 7 is one 5 with 2 left over
console.log(5 % 5); // 0
console.log(2 % 5); // 2
Rotating a list of 5 by 7 steps is the same as rotating it by 2, because 5 of those steps bring you right back to the start. 7 % 5 gives you that 2.
A rotation is two slices swapped
Rotating left by 2 means: take everything from index 2 onwards, then put the first two items after it.
const xs = [1, 2, 3, 4, 5];
console.log(xs.slice(2)); // [ 3, 4, 5 ]
console.log(xs.slice(0, 2)); // [ 1, 2 ]
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
24 Rotate a list by k places
fairRotate [1, 2, 3, 4, 5] left by 2 to get [3, 4, 5, 1, 2]. It must cope with k larger than the list and with a negative k.
Stuck? Three hints, smallest first
- 1. A rotation is two slices swapped round, which is one line once you know the offset.
- 2.
k % nhandles a largekbut not a negative one: the remainder keeps the sign. - 3.
((k % n) + n) % nis the standard fix, and it is worth writing once.
Step 1: rotate by a small k
Join the two slices with spread, back part first.
function rotate(xs, k) {
return [...xs.slice(k), ...xs.slice(0, k)];
}
const xs = [1, 2, 3, 4, 5];
console.log(rotate(xs, 2)); // [ 3, 4, 5, 1, 2 ]
console.log(rotate(xs, 0)); // [ 1, 2, 3, 4, 5 ]
console.log(rotate(xs, 7)); // [ 1, 2, 3, 4, 5 ], should be the same as by 2
For 2 and 0 it works. For 7 it does nothing, because slice(7) is past the end and comes back empty. We need to wrap k into the range 0 to 4 first.
Step 2: wrap a large k
function rotate(xs, k) {
const shift = k % xs.length;
return [...xs.slice(shift), ...xs.slice(0, shift)];
}
const xs = [1, 2, 3, 4, 5];
console.log(rotate(xs, 7)); // [ 3, 4, 5, 1, 2 ]
console.log(rotate(xs, 5)); // [ 1, 2, 3, 4, 5 ]
console.log(rotate(xs, -1)); // [ 5, 1, 2, 3, 4 ]
Now 7 works, and rotating by the length gives the list back unchanged. The last line even looks right: a negative k should rotate the other way, to the right, and [5, 1, 2, 3, 4] is right by one.
It only looks right by luck. Look at what shift is:
console.log(-1 % 5); // -1
console.log(-6 % 5); // -1
JavaScript's % keeps the sign of the number on the left, so the remainder is still negative. slice(-1) happens to count back from the end, which is why the answer came out right. The code is right by accident. The moment you use shift for anything else, it breaks:
const xs = [1, 2, 3, 4, 5];
const shift = -1 % xs.length;
console.log(xs[shift]); // undefined: square brackets don't count from the end
We want shift to always be a real index, a number from 0 to n - 1.
Step 3: the double remainder
Here is the standard fix:
const n = 5;
console.log(((-1 % n) + n) % n); // 4
console.log(((7 % n) + n) % n); // 2
console.log(((2 % n) + n) % n); // 2
Read it from the inside out. -1 % 5 is -1. Adding 5 gives 4, which is no longer negative. The final % 5 handles the case where the first remainder was already positive, so adding 5 pushed it too high: 2 + 5 is 7, and 7 % 5 is back to 2.
Rotating left by 4 is the same as rotating right by 1, so 4 is the correct shift for -1. This pattern, ((k % n) + n) % n, means "wrap any whole number into 0 to n - 1". You will see it again in anything that goes round in a circle, like a playlist on repeat.
Step 4: put it together
One more case: an empty list. k % 0 is NaN, so return early.
function rotate(xs, k) {
const n = xs.length;
if (n === 0) return [];
const shift = ((k % n) + n) % n;
return [...xs.slice(shift), ...xs.slice(0, shift)];
}
const xs = [1, 2, 3, 4, 5];
console.log(rotate(xs, 2)); // [ 3, 4, 5, 1, 2 ]
console.log(rotate(xs, -1)); // [ 5, 1, 2, 3, 4 ]
console.log(rotate(xs, 7)); // [ 3, 4, 5, 1, 2 ]
console.log(rotate([], 3)); // []
console.log(xs); // [ 1, 2, 3, 4, 5 ]
The last line shows the input was never changed. slice copies, and spread builds a brand new array.
The full solution
The panel has the final rotate, runs it with 2, 0, -1 and 7, and prints the two remainders side by side so you can see why the double remainder is needed. Press Run.
function rotate(xs, k) {
const n = xs.length;
if (n === 0) return [];
const shift = ((k % n) + n) % n; // normalise: large k, negative k, both
return [...xs.slice(shift), ...xs.slice(0, shift)];
}
const xs = [1, 2, 3, 4, 5];
console.log('left by 2 :', rotate(xs, 2));
console.log('left by 0 :', rotate(xs, 0));
console.log('right by 1 :', rotate(xs, -1), '<- a negative k goes the other way');
console.log('by 7 on 5 :', rotate(xs, 7), 'same as by 2');
console.log('--- why the double modulo ---');
console.log('-1 % 5 =', -1 % 5, '<- still negative, so slice would read from the end');
console.log('((-1 % 5) + 5) % 5 =', ((-1 % 5) + 5) % 5);
console.log('input afterwards :', xs);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('rotating left by 2', rotate(xs, 2), [3, 4, 5, 1, 2]);
test('rotating by 0 changes nothing', rotate(xs, 0), [1, 2, 3, 4, 5]);
test('a negative k rotates right', rotate(xs, -1), [5, 1, 2, 3, 4]);
test('a k larger than the length wraps round', rotate(xs, 7), rotate(xs, 2));
test('rotating by the length is a no-op', rotate(xs, 5), [1, 2, 3, 4, 5]);
test('the plain remainder keeps the minus sign', -1 % 5, -1);
test('which is what the double modulo repairs', ((-1 % 5) + 5) % 5, 4);
test('an empty list is safe', rotate([], 3), []);
test('the input is never modified', xs, [1, 2, 3, 4, 5]);
Also Basic 46. The angle here is the offset arithmetic, because that is where rotations actually go wrong. JavaScript's % is a remainder, not a modulo: it keeps the sign of the left operand, so -1 % 5 is -1. Feed that to slice and you get a negative index, which silently counts from the other end and produces a plausible-looking wrong answer.
((k % n) + n) % n is the idiom for "wrap into 0..n-1". It is worth recognising on sight — it shows up in ring buffers, in circular queues, and any time an index cycles.
Common mistakes
- Using
k % nalone. It leaves negative numbers negative.slicehappens to cope, as Step 2 showed, butxs[shift]or any other use of that number gives the wrong result. - Forgetting the empty list.
k % 0isNaN. Return an empty array before doing any maths. - Rotating in place with a loop of
shiftandpush. That changes the caller's array and takesksteps. Two slices do it in one go and leave the input alone.
Try it yourself
- Write
rotateRight(xs, k)using yourrotate. (Hint: one character.) - A week starts on Monday in one country and Sunday in another. Rotate
['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']so it starts on Monday. - Use the double remainder to write
nextIndex(i, n)andprevIndex(i, n)for a carousel ofnslides.