Array rotation is one of those deceptively simple problems that reveal how well you really understand arrays and modular arithmetic. Let’s explore intuitive, language agnostic ways to perform left and right rotations efficiently, without getting lost in syntax.
What Is Array Rotation?
Array rotation means shifting elements circularly so that none are lost, they just “wrap around.”
For example, rotating [1, 2, 3, 4, 5] left by 2 positions gives [3, 4, 5, 1, 2].
Rotating it right by 2 would give [4, 5, 1, 2, 3].
It’s a tiny concept but shows up in scheduling systems, circular queues, and countless interview questions.
Left Rotation — The Straightforward Way
Move each element to (i - d) % n position.
// Left rotate array by d positions
for i from 0 to n-1:
newIndex = (i - d + n) % n
result[newIndex] = arr[i]
return result
Simple to understand, Uses extra O(n) space
Use this when clarity matters more than optimization.
Right Rotation — Just the Mirror
A right rotation by d is simply a left rotation by (n - d).
// Right rotate array by d positions
leftD = (n - d) % n
perform left rotation by leftD
It’s that simple — reuse your left rotation logic!
The Reversal Trick — In-Place & Elegant
Want O(1) extra memory? Try the reversal algorithm.
// Left rotate array by d
reverse(arr[0..d-1])
reverse(arr[d..n-1])
reverse(arr[0..n-1])
By reversing parts and then the whole, you end up with the array rotated perfectly in place.
Clean, clever, and efficient.
This one’s based on cycles in array positions, using GCD logic.
g = gcd(n, d)
for start from 0 to g-1:
temp = arr[start]
current = start
while True:
next = (current + d) % n
if next == start:
break
arr[current] = arr[next]
current = next
arr[current] = temp
This approach avoids extra space and is faster for large arrays.
Pro Tips
- Always normalize:
d = d % n
- Negative rotations? Convert with
d = (d + n) % n
- For interviews — know at least two methods: simple & in-place.
Want Full Code and Visuals?
This article is just the conceptual primer.
For step-by-step visuals and runnable code in C++, Python & JS, read my detailed write-up here
\[Read the full Medium article on Array Rotations\]