DocsHub
Animations

Rotate Array — Visual Walkthrough

Watch how slicing splits the array at the right position and rejoins the two parts in reversed order.

Rotate Array

Array: [1, 2, 3, 4, 5, 6, 7]Rotate right by k = 3

The last k elements move to the front. The rest shift right. Slicing makes this a one-liner.

Rotate Arrayslicing · O(n)
rotate right byk = 3

Input array — split into two parts

1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
6
[5]
7
[6]
n7
k (normalized)3
split at index4
rotate_array.py
def rotate_right(arr, k):
n = len(arr)
k = k % n # normalize
last_k = arr[-k:] # last k elements
first_part = arr[:-k] # rest
result = last_k + first_part
return result
Call rotate_right([1, 2, 3, 4, 5, 6, 7], k=3)
step 0/6
0%

How it works

def rotate_right(arr, k):
    n = len(arr)
    k = k % n                    # handle k > n

    last_k = arr[-k:]            # last k elements
    first_part = arr[:-k]        # everything else

    return last_k + first_part   # rejoin

arr[-3:] takes the last 3 elements. arr[:-3] takes everything except the last 3. Concatenating them in reverse order gives the rotation.

k = k % n handles cases where k is larger than the array. Rotating an array of 7 elements by 7 brings you back to the start — same as k=0. Rotating by 10 is the same as rotating by 3.

Complexity

TimeSpace
SlicingO(n)O(n)
In-place reversalO(n)O(1)

On this page