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

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. 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

  1. Choose how many positions, k, to rotate by (use k modulo array length to handle large k).
  2. Take the first k elements and remember them separately (or conceptually as the 'front chunk').
  3. Take the remaining elements after position k (the 'back chunk').
  4. Place the back chunk first, followed by the front chunk.

Rotate Left Worked Example

Input: Rotate [1, 2, 3, 4, 5] left by 2

  1. Front chunk (first 2 elements): [1, 2]
  2. Back chunk (remaining elements): [3, 4, 5]
  3. Place back chunk then front chunk: [3, 4, 5] + [1, 2]

Output: [3, 4, 5, 1, 2]

Try your own input
Rotate LeftO(n)
Moves the front element to the back, one step at a time, for the chosen number of shifts.
1
0
2
1
3
2
4
3
5
4
Active / shifting Result
Rotate Left
Press ▶ Run to watch it step by step.
Python · Arrays in Code
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]
Input: Rotate [1, 2, 3, 4, 5] left by 2

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

TimeO(n)
SpaceO(1) extra space if rotated in-place using the reversal trick, O(n) with a helper array

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.