Rotate an Array by K Positions
Table of Contents + β
This one looks easy. You just shift things to the right, right? But the interviewer is not watching the answer. They are watching how you save space. Anyone can make a new array and copy stuff into it. The real test is this. Can you rotate it without that extra array? So let us talk it through the way you would in the room.
π The Problem
You get an array and a number k. You have to move every element to the right by k places. The elements that fall off the right end come back around to the front. We call this rotation, which just means shifting elements in a circle.
Here is a small example so you can see it clearly.
Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3Output: [5, 6, 7, 1, 2, 3, 4]See what happened? The last three numbers 5, 6, 7 jumped to the front. Everything else slid over to make room. One small thing to set up front. We assume the array has at least one element. An empty array has nothing to rotate.
π’ The Brute-Force Way
The first idea most people get is simple. Rotate the array by just one step. Then do that k times. So if k is 3, you shift everything one place to the right, three separate times.
It works. But think about the cost. Each single shift touches all n elements. And you do it k times. So the total work is n times k. If the array is big and k is big, this gets slow fast. We write that as O(n*k).
π¦ The Extra-Array Way
A faster idea is to use a second array. You walk through the original. For each element, you figure out where it should land after rotation and you place it there in the new array. Then you copy the new array back.
This is fast. It only does O(n) work. But it uses a whole second array of size n. So the space cost is O(n). The interviewer will smile and then ask the real question. βCan you do it without that extra array?β That is where the next trick comes in.
π The Optimal Way: The Reversal Trick
Here is the clever part. You can rotate the array in place using only reversal, which means flipping a section of the array so it reads backwards.
The trick has three reversals. Take [1, 2, 3, 4, 5, 6, 7] with k = 3.
Step 1 - reverse the whole array: [7, 6, 5, 4, 3, 2, 1]Step 2 - reverse the first k: [5, 6, 7, 4, 3, 2, 1]Step 3 - reverse the rest: [5, 6, 7, 1, 2, 3, 4]And there it is. The answer falls right out. No extra array needed.
One thing you must never forget. Sometimes k is bigger than the array length. Rotating an array of 7 by 10 is the same as rotating it by 3. So before anything else, do k = k % n. This keeps k inside the array size. Forgetting this is the most common bug in this problem.
Caution
If you skip k = k % n and someone passes a big k, your code will read past the array and crash. Always shrink k first. This step assumes the array has at least one element, since k % n itself would fail when n is 0.
Steps to rotate using reversal
- Set
k = k % nsoknever goes past the array length. - Reverse the entire array from start to end.
- Reverse the first
kelements. - Reverse the remaining
n - kelements. - The array is now rotated to the right by
k.
# Reverse the part of the list from index left to index right.def reverse(arr, left, right): while left < right: arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1
def rotate(arr, k): n = len(arr) k = k % n # keep k inside the array size reverse(arr, 0, n - 1) # reverse the whole array reverse(arr, 0, k - 1) # reverse the first k reverse(arr, k, n - 1) # reverse the rest
nums = [1, 2, 3, 4, 5, 6, 7]rotate(nums, 3)print(nums)The output of the above code will be:
[5, 6, 7, 1, 2, 3, 4]β±οΈ Time and Space Complexity
So how do these three ways stack up? Here is the side by side.
| Approach | Time | Space |
|---|---|---|
| One step, k times | O(n*k) | O(1) |
| Extra array | O(n) | O(n) |
| Reversal trick | O(n) | O(1) |
The reversal trick wins. It is fast like the extra-array way, but it uses O(1) space, which means no extra space at all.
Tip
If the interviewer says any library is fine, Python has collections.deque with a rotate method, and many languages have built-in slice tricks. But say it out loud first. βI can use the built-in, but let me show you the reversal method so you can see the logic.β That is what they want to hear.
π§© Key Takeaways
- β
Always do
k = k % nfirst, so a bigkdoes not break your code. - β The brute-force βone step k timesβ is simple but slow at O(n*k).
- β The extra-array way is fast but spends O(n) extra space.
- β The reversal trick gives you O(n) time and O(1) space, which is the answer interviewers want.
- β
Reversal trick in order: reverse the whole array, reverse the first
k, then reverse the rest.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Why must you compute k = k % n before rotating?
Why: If k is bigger than n, rotating by k is the same as rotating by k % n, and skipping this can read past the array.
- 2
What is the time complexity of rotating one step, k times?
Why: Each single-step shift touches all n elements, and you repeat it k times, giving O(n*k).
- 3
In the reversal trick, what is the correct order of the three reversals?
Why: You reverse the entire array, then the first k elements, then the remaining elements.
- 4
What is the space complexity of the reversal trick?
Why: The reversal trick swaps elements in place, so it uses constant extra space.