Quick revision
The short answer
Rotating an array right by k is an in-place arrays problem solved with three reversals. After reducing k modulo n, we reverse the whole array, which brings the last k values to the front in backward order, then reverse the first k positions and the remaining n - k to restore the order inside each block. That is O(n) time and O(1) extra space.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Rotate by one place, k times | O(n * k) | O(1) |
| Copy into a second array with (i + k) % n | O(n) | O(n) |
| Three reversals | O(n) | O(1) |
What to remember
We rotated an array right by k in place by seeing the rotation as a swap of two blocks, the first n - k values and the last k. Reversing the whole array puts both blocks in the right place, backwards, and reversing each block on its own restores their order. Reducing k with the modulo first, and turning a negative k into a right rotation, keeps every index inside the array. It costs O(n) time and O(1) extra space. The clue to remember is an in-place rearrangement that swaps two blocks but keeps the order inside each: reverse the whole, then reverse the parts.
1What it means to rotate an array to the right
Picture a shelf with seven books standing in a row, numbered 1 to 7 from left to right. Rotating the shelf right by one means every book moves one place to the right, and the book that falls off the right end, book 7, is carried round and put at the left end. Rotating right by three means doing that three times, so books 5, 6 and 7 end up at the front, still in their own order, and books 1 to 4 end up after them.
In the question, the shelf is an array and the books are its values. After rotating right by k, the value that was at index i sits at index (i + k) mod n, where n is the length and mod means the remainder after dividing. The remainder is what makes values wrap round: for i = 5, n = 7 and k = 3, (5 + 3) mod 7 is 1, so the value 6 lands at index 1.
This problem is gentle once you see it, so please do not worry about the word rotate. The hard part is only the extra rule that interviewers usually add: do it in place, which means inside the same array, using only a few extra variables. On the shelf that is like being allowed to hold just one book in your hand at a time.
Let us keep one example for the whole article: [1, 2, 3, 4, 5, 6, 7] with k = 3. Work it out with the formula. 1 at index 0 goes to index 3, 2 goes to 4, 3 to 5, 4 to 6, 5 at index 4 wraps to (4 + 3) mod 7 = 0, 6 to 1 and 7 to 2. So the answer is [5, 6, 7, 1, 2, 3, 4].
Top row: the array we are given. Bottom row: the same array rotated right by 3 positions.
- n
- 7
- k
- 3
- rule
- i -> (i + k) % n
1The last three values, 5, 6 and 7, move to the front in their own order, and 1, 2, 3 and 4 slide three places to the right.
What to assume
- Can k be larger than the length?
- Yes, and only k mod n matters: rotating by 10 is the same as rotating by 3 when the length is 7.
- Can k be zero or negative?
- Zero leaves the array alone, and we treat a negative k as a left rotation.
- Must we rotate in place?
- Yes, and we return nothing. An empty array we simply leave alone.
A careful candidate asks a few questions first. Can k be larger than the length? Yes, and rotating seven books by 7 puts every book back where it started, so only k mod n matters: rotating by 10 is the same as rotating by 3. Can k be zero or negative? Zero leaves the array alone, and we will treat a negative k as a left rotation. Must we rotate in place? We will, and return nothing. And an empty array we simply leave alone.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise this arrays problem
A beginner who reads this question usually thinks of moving values one at a time, perhaps with the formula, perhaps by shifting the whole row over and over. Both are fair first ideas, and we will try them next. The trouble starts with the words in place, because moving a value into its new home overwrites whatever was living there.
So let us read the question for clues, one at a time. The first clue is the phrase rotate an array. Write the answer under the question and compare: [1, 2, 3, 4, 5, 6, 7] became [5, 6, 7, 1, 2, 3, 4]. Look at it as two blocks. The front block, 1 to 4, and the back block, 5 to 7, have simply changed places, and inside each block the order did not change at all.
The second clue is the phrase by k positions. The value of k decides where the boundary between the two blocks lies: the back block is the last k values. So whatever we do should work on blocks of length k and n - k, and k must first be reduced by mod n so that the boundary falls inside the array.
The third clue is the unspoken in place. Swapping two values needs only one spare variable, and reversing a stretch of an array is just a series of swaps from the two ends inwards. Reversal is the simplest in-place rearrangement there is, so it is worth asking whether a few reversals can produce the block swap.
This question is filed under the arrays and hashing pattern, the family of problems solved by working directly on an array, sometimes with a hash map beside it. Here no hash map is needed; the tool is index arithmetic and reversal. The rule to carry to new problems is that when an in-place rearrangement swaps two blocks but keeps the order inside each, reverse the whole array and then reverse each block. Reversing the words of a sentence in place uses the same rule.
Two neighbours look similar. Two pointers walking towards each other is exactly what each reversal does inside, so it is part of the answer rather than a rival. And a deque, a list you can add to and remove from at both ends, can rotate by moving values from the back to the front, but that copies the data into a new structure, which the in-place rule forbids.
3The honest first attempts, shifting one place at a time and copying
The most natural first attempt follows the shelf exactly. Rotate right by one place: hold the last book in your hand, slide every other book one place to the right, starting from the right end so nothing is overwritten, and put the held book at the front. Then do that k times. It is in place, it is easy to check, and it is a good honest start. The second attempt, below it, uses the formula with a second array: put each a[i] straight into result[(i + k) % n], then copy result back.
Highlighted values have been carried round to the front; compared values have been shifted again. Watch the move count grow.
- rotations
- 0
- moves
- 0
1We start from 1 to 7. Each rotation by one place will shift every book one step right and carry the last book round to the front.
- rotations
- 1
- moves
- 7
2After the first rotation, 7 has come round to the front and 1 to 6 have each moved one step. That took 7 moves.
- rotations
- 2
- moves
- 14
3After the second rotation, 6 comes round to the front. Notice that 1 to 5 have now been moved twice. Running total, 14 moves.
- rotations
- 3
- moves
- 21
4After the third rotation the shelf reads 5, 6, 7, 1, 2, 3, 4, the right answer, but 1 to 4 were each moved three times to travel three places.
Let us count the first attempt on the example. One rotation moves all seven values once, seven moves. Three rotations make 21 moves, as the picture shows, to achieve something that needs each value to move only once. In general each rotation is n moves and there are k of them, so the time is O(n times k), read as order n times k. When k is close to n, that is O(n squared). The extra space is one variable, O(1).
Where is the waste? Look at book 1 in the picture. To travel three places it was moved three separate times, one step each, and the same is true of books 2, 3 and 4. Every value takes k small steps when one big step would do.
The copying attempt fixes the time. Each value is placed directly in its new home, so it is O(n) time, and it is a perfectly good answer to give first. But it needs a second array of n values, so its extra space is O(n). Why can we not just write a[(i + k) % n] = a[i] inside the same array? Let us try it: putting 1 into index 3 overwrites 4 before 4 has been moved, and 4 is lost. The copy exists only to protect the values we have not moved yet.
So the question becomes whether we can place every value in roughly one move, as the copy does, while holding only one value in our hand, as the shifting does.
4Getting to three reversals, one observation at a time
Let us return to the observation about blocks. Call the front block A = [1, 2, 3, 4] and the back block B = [5, 6, 7]. The array is A followed by B, and we want B followed by A, each block in its original order.
Now think about what reversing the whole array does. Reversing [1, 2, 3, 4, 5, 6, 7] gives [7, 6, 5, 4, 3, 2, 1]. Look at the front three positions: 7, 6, 5. Those are exactly the values of B, now at the front where they belong, only backwards. And the back four positions hold 4, 3, 2, 1, the values of A, at the back where they belong, also backwards. One reversal has put both blocks in the right place.
A beginner naturally asks how we fix the backward order without undoing the move. The answer is to reverse each block on its own. Reversing the first k = 3 positions turns 7, 6, 5 into 5, 6, 7, and it touches nothing outside those three positions. Reversing the remaining n - k = 4 positions turns 4, 3, 2, 1 into 1, 2, 3, 4. The array is now [5, 6, 7, 1, 2, 3, 4], the rotation.
Why does this always work, and not only for our numbers? Reversing a whole sequence A followed by B gives the reverse of B followed by the reverse of A, because the last value comes first, and the last values are B's. Reversing a sequence twice gives back the original. So reversing each part a second time turns the reverse of B into B and the reverse of A into A, which leaves B followed by A.
Each reversal needs only the swap routine. We put one index, from, at the start of the range and another, to, at the end, swap the two values using one spare variable, move from right and to left, and stop when they meet. That is the one book in the hand.
There is one trap to remember. The boundary between the blocks is at k, so k must be reduced first with k %= n. If we forget and call with k = 10 on seven values, the second reversal is asked to reverse positions 0 to 9, which do not exist, and Java throws an ArrayIndexOutOfBoundsException.
5Watching the three reversals on the example
The picture below plays the method on [1, 2, 3, 4, 5, 6, 7] with k = 3, one swap per frame. Under the cells, from and to mark the two ends that were just swapped. The compared cells are the range the current reversal is working on, and in the last steps the front block, already final, is marked as done.
Watch the front three positions after the third frame. From that moment they hold 5, 6 and 7, only in the wrong order, and the remaining frames do nothing but tidy the order inside each block.
from and to are the two ends being swapped. Compared cells are the range being reversed; done cells are already final.
- k
- 3
- step
- not started
1We begin with 1 to 7 and k = 3. The front block A is 1, 2, 3, 4 and the back block B is 5, 6, 7. We want B first, then A, each in its own order.
- k
- 3
- step
- 1: reverse 0..6
- swapped
- 1 and 7
2Step 1 reverses the whole array. from starts at 0 and to at 6, so we swap 1 and 7, then move both pointers one step inward.
- k
- 3
- step
- 1: reverse 0..6
- swapped
- 2 and 6
3Next we swap positions 1 and 5, so 2 and 6 change places. The pointers move inward again, to 2 and 4.
- k
- 3
- step
- 1: reverse 0..6
- swapped
- 3 and 5
4We swap 3 and 5 at positions 2 and 4. Moving inward, both pointers would land on 3, so they have met and the reversal stops. The block 7, 6, 5 is already at the front, but backwards.
- k
- 3
- step
- 2: reverse 0..2
- swapped
- 7 and 5
5Step 2 reverses the first k = 3 positions. One swap of positions 0 and 2 turns 7, 6, 5 into 5, 6, 7, the right order for the front.
- k
- 3
- step
- 3: reverse 3..6
- swapped
- 4 and 1
6Step 3 reverses the remaining positions 3 to 6. The first swap exchanges 4 and 1, at positions 3 and 6.
- k
- 3
- step
- 3: reverse 3..6
- swapped
- 3 and 2
7The second swap exchanges 3 and 2, at positions 4 and 5. The pointers meet, and the back block reads 1, 2, 3, 4.
- k
- 3
- swaps
- 6
- answer
- [5, 6, 7, 1, 2, 3, 4]
8All three reversals are done with six swaps and one spare variable. The array is now 5, 6, 7, 1, 2, 3, 4, the rotation by 3.
Let us read the important frames back. In the second to fourth frames, the whole reversal swaps 1 with 7, 2 with 6 and 3 with 5. The middle value, 4, never moves, because from and to meet on it. Three swaps reversed seven values.
The fifth frame is the whole second reversal: the range 0 to 2 has only one pair to swap, 7 and 5, and the middle value 6 stays put. After it, the front reads 5, 6, 7 and will not change again.
The sixth and seventh frames reverse the back block 4, 3, 2, 1 with two swaps. In all we made six swaps, each moving two values, and held only one value in the spare variable at any time.
6The complete Java program
Here is the full program. rotate changes the array in place and returns nothing, and reverse is the small swapping helper. main rotates the example by 3 and by 10, which must agree, by 0, and by -1, which is a left rotation by one, and each comment shows what that line prints.
Let us read rotate in the order it runs. First we take n, the length, and return at once if it is 0. That early return matters, because the next line computes k % n, and dividing by zero would throw an exception. Then k %= n reduces k to the range we need, so 10 becomes 3.
The next line handles a negative k. In Java, -1 % 5 is -1, not 4, so after the modulo a negative k stays negative. A left rotation by one is the same as a right rotation by n - 1, so adding n turns -1 into 4, and the rest of the method only ever sees a right rotation between 0 and n - 1.
Then come the three reversals, in the order we worked out: the whole array, positions 0 to k - 1, and positions k to n - 1. When k is 0, the middle call is reverse(a, 0, -1), whose loop never runs, and the first and last calls both reverse the whole array, which puts it back as it was.
reverse is the swap routine. While from is less than to, it saves a[from] in tmp, copies a[to] into a[from] and moves from right with from++, then puts tmp into a[to] and moves to left with to--. So main prints [5, 6, 7, 1, 2, 3, 4] twice, then [1, 2], then [2, 3, 4, 5, 1].
7How much it costs, and the cases at the edges
Let us count on the example first. The three reversals made 3, 1 and 2 swaps, six in all, and each swap moves two values, so twelve moves for seven values. In general the first reversal makes about n / 2 swaps and the other two together make about n / 2 more, so roughly n swaps in total and the time is O(n). We use from, to and tmp, whatever the length, so the extra space is O(1).
| Approach | Time | Extra space |
|---|---|---|
| Rotate by one place, k times | O(n * k) | O(1) |
| Copy into a second array with (i + k) % n | O(n) | O(n) |
| Three reversals | O(n) | O(1) |
Now the edges. An empty array returns at the first line, before the division. A single value is unchanged for any k, because k % 1 is 0. A k larger than n is reduced by the modulo, which is why rotating by 10 printed the same as rotating by 3. A k that is a whole multiple of n becomes 0 and leaves the array as it was.
A negative k becomes a right rotation by n + k, so rotating [1, 2, 3, 4, 5] by -1 gives [2, 3, 4, 5, 1], the left rotation main prints. The one bug to guard against is forgetting the modulo, which sends the reversals outside the array for any k bigger than n.
8Follow-up questions
Is there another way to rotate in place?
Yes, the cyclic replacement method. Starting at index 0, we pick up its value and carry it to its new home (0 + k) mod n, pick up the value that was there, carry that one to its home, and so on until we come back to the start. When n and k share a common factor, as with n = 6 and k = 2, one cycle visits only some positions, so we start a new cycle from index 1, then 2, until n values have moved. It is also O(n) time and O(1) space, but the extra cycles make it easier to get wrong than the reversals.
How would you rotate to the left by k?
A left rotation by k is the same as a right rotation by n - k, which is how our code treats a negative k. Directly, we can reverse the first k values, reverse the rest, and then reverse the whole array, the same three reversals in a different order. For a List, Collections.rotate does the job, with a positive distance meaning a rotation to the right.
Where else does the reversal trick appear?
Reversing the order of words in a sentence in place is the same idea: reverse the whole string, so the words are in the right order but each one is spelled backwards, and then reverse each word on its own. It is also a way to swap two neighbouring blocks of memory of different sizes without a second buffer.
9Conclusion
We rotated an array right by k in place by seeing the rotation as a swap of two blocks, the first n - k values and the last k. Reversing the whole array puts both blocks in the right place, backwards, and reversing each block on its own restores their order. Reducing k with the modulo first, and turning a negative k into a right rotation, keeps every index inside the array. It costs O(n) time and O(1) extra space. The clue to remember is an in-place rearrangement that swaps two blocks but keeps the order inside each: reverse the whole, then reverse the parts.
Open with
I will rotate in place and return nothing. First I reduce k modulo n, since rotating by n is a full circle, and if k is negative I add n to turn a left rotation into a right one.
Then, if they want more
An empty array I leave alone, which also avoids dividing by zero. Shifting by one place k times works in O(1) space but costs O(n times k), and copying each value to index i plus k mod n in a second array is O(n) time but O(n) space.
To get both, I see the rotation as swapping two blocks: the first n minus k values and the last k values, each keeping its own order. Reversing the whole array puts the last k values at the front and the rest at the back, both backwards.
Then I reverse the first k positions and the remaining n minus k positions, which restores the order inside each block. Each reversal is a two-pointer swap loop with one temporary variable.
On 1 to 7 with k equal to 3, the whole reversal gives 7 down to 1, and the two partial reversals give 5, 6, 7, 1, 2, 3, 4. That is O(n) time, about n swaps, and O(1) extra space.
About this answer
- Last updated
- 14 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 22 times in that collection. How it is counted
- Official documentation
- Arrays (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Rotate an array to the right by k positions.": https://scrivio-interview-library.netlify.app/data-structures/solutions/rotate-an-array-to-the-right-by-k-positions-e51109/