← All Lessons Lesson 32 / 68
Lesson 32

Rotating an Array to the Right by k Steps

Rotating an Array to the Right by k Steps

Imagine you have a row of numbered boxes lined up on a shelf. "Rotating to the right" means every box slides one spot to the right, and the box that falls off the right end comes back around to the very front. Do this k times, and you have rotated the array by k steps.

What the problem asks

You are given an array arr and a number k (which is zero or a positive number). You must shift the array k steps to the right.

For example:

  • Input: arr = [1, 2, 3, 4, 5], k = 3
  • Output: [3, 4, 5, 1, 2]

Watching it happen one step at a time

A "right rotation" by one step takes the last element and puts it at the front, while everything else moves one place to the right. Let's rotate [1, 2, 3, 4, 5] three times:

  1. Rotate 1 step → [5, 1, 2, 3, 4] (the 5 jumped to the front)
  2. Rotate 2 steps → [4, 5, 1, 2, 3] (now the 4 jumped to the front)
  3. Rotate 3 steps → [3, 4, 5, 1, 2] (now the 3 jumped to the front)

After 3 steps we reach the answer [3, 4, 5, 1, 2]. Notice the pattern: the last k numbers (3, 4, 5) end up at the front, and the first part (1, 2) slides to the back.

The important rule: do it in-place

The problem adds a strict condition. You must change the same array that was given to you, without creating a new full-size array to hold the answer. This is called working in-place, and it means you may only use a tiny, fixed amount of extra memory — no matter how big the array is.

In plain words: you are allowed a few helper variables (like one temporary box), but you are not allowed to make a second copy of the whole array. This requirement is written as O(1) space complexity. The O(1) simply means "the extra memory you use stays constant" — it does not grow when the array grows.

The starting code

You are asked to fill in a function. Here is the skeleton you begin with:

using namespace std;

class Solution {
public:
    void kRotations(vector<int> &arr, int k)
    }
};

Notice the & in vector<int> &arr. That & means the array is passed by reference — the function works on the real array, not a copy. So any change you make inside the function directly updates the original arr. That is exactly what lets you rotate it "in-place."

A small but useful tip for later: if k is larger than the array's length, rotating fully around brings you back to the start. So rotating by k gives the same result as rotating by k divided by the length's remainder. Keeping this in mind avoids doing extra, wasted work.

Rotating an Array to the Right by k Steps
Diagram — click to zoom (scroll / drag to pan)