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

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

  1. Choose how many positions, k, to rotate by (use k modulo array length to handle large k).
  2. Take the last k elements as the 'back chunk'.
  3. Take the remaining elements before that as the 'front chunk'.
  4. Place the back chunk first, followed by the front chunk.

Rotate Right Worked Example

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

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

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

Try your own input
Rotate RightO(n)
Moves the back element to the front, 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 Right
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 right 2 on [1, 2, 3, 4, 5]
Input: Rotate [1, 2, 3, 4, 5] right 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 Right 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 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

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.