Data Structures · Visualization
Rotate Left
Array
Rotating an array left by k positions moves each element k spots toward the front, and the elements that fall off the front wrap around to the back. 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 Left
ArrayRotating an array left by k positions moves each element k spots toward the front, and the elements that fall off the front wrap around to the back. A simple way to picture it: chop the array into two pieces at position k, then swap the order of the two pieces.
How Rotate Left Works
- Choose how many positions, k, to rotate by (use k modulo array length to handle large k).
- Take the first k elements and remember them separately (or conceptually as the 'front chunk').
- Take the remaining elements after position k (the 'back chunk').
- Place the back chunk first, followed by the front chunk.
Rotate Left Worked Example
Input: Rotate [1, 2, 3, 4, 5] left by 2
- Front chunk (first 2 elements): [1, 2]
- Back chunk (remaining elements): [3, 4, 5]
- Place back chunk then front chunk: [3, 4, 5] + [1, 2]
Output: [3, 4, 5, 1, 2]
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 left 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 Left Time & Space Complexity
When to Use Rotate Left
- Cycling through a playlist or carousel of images
- Scheduling algorithms that rotate whose turn is next
- Shifting a buffer of recent events in a circular log
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.