Data Structures · Visualization
Rotate Right
Array
Rotating an array right by k positions moves each element k spots toward the end, and the elements that fall off the back wrap around to the front. Time: O(n). Space: O(1) extra space if rotated in-place using the reversal trick, O(n) with a helper array.
Big-O: Random access O(1); insert/delete in the middle O(n).
Rotate Right
ArrayRotating an array right by k positions moves each element k spots toward the end, and the elements that fall off the back wrap around to the front. It is the mirror of rotating left: split the array into a 'back chunk' of the last k elements and a 'front chunk' of the rest, then put the back chunk first.
How Rotate Right Works
- Choose how many positions, k, to rotate by (use k modulo array length to handle large k).
- Take the last k elements as the 'back chunk'.
- Take the remaining elements before that as the 'front chunk'.
- Place the back chunk first, followed by the front chunk.
Rotate Right Worked Example
Input: Rotate [1, 2, 3, 4, 5] right by 2
- Back chunk (last 2 elements): [4, 5]
- Front chunk (remaining elements): [1, 2, 3]
- Place back chunk then front chunk: [4, 5] + [1, 2, 3]
Output: [4, 5, 1, 2, 3]
Press ▶ Run to watch it step by step.
def rotate_left(arr, k):
k %= len(arr)
return arr[k:] + arr[:k]
def rotate_right(arr, k):
k %= len(arr)
return arr[-k:] + arr[:-k]
# O(n) time, O(n) extra space
# example: rotate right 2 on [1, 2, 3, 4, 5]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Rotate Right Time & Space Complexity
When to Use Rotate Right
- Shifting recent items into view in a circular buffer or carousel
- Implementing 'undo/redo' style position wrapping
- Cryptographic and encoding algorithms that use cyclic shifts
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.