Skip to content
BytePatterns

Rotate an Array

Arrays: lesson 13 of 14

Three reversals move every element home.

Lesson 13 of 14 · 4 min

Rotate an Array

Step 1 of 8

Rotate right by k = 2: the last two values have to end up at the front, in order.

The Idea

Rotating right by k means the last k values jump to the front. Reverse the whole array and they are at the front already — backwards, and so is everything else. Now reverse the first k, then reverse the rest, and both blocks read correctly again. Three linear reversals, no copy of the array, and k taken modulo the length so a full turn costs nothing.

Real-World Example

A display board cycles a queue of adverts every few seconds. Instead of copying the whole queue on each tick, the renderer flips it end to end and flips the two blocks back — the same memory, and nothing allocated on a path that runs all day.

The Code

def rotate(nums, k):
    k %= len(nums)

    def reverse(lo, hi):
        while lo < hi:
            nums[lo], nums[hi] = nums[hi], nums[lo]
            lo, hi = lo + 1, hi - 1

    reverse(0, len(nums) - 1)   # flip the whole row
    reverse(0, k - 1)           # put the first block back in order
    reverse(k, len(nums) - 1)   # and the rest
    return nums

print(rotate([1, 2, 3, 4, 5], 2))   # [4, 5, 1, 2, 3]

Python

Your turn

Fill in the blank.

k %= len(nums)
reverse(0, len(nums) - 1)
reverse(0, k - 1)
reverse(k, ___)

Mini quiz

1 / 3

Why is k reduced modulo the array length?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.