Rotate Right by 1

Rotate array right by one position.

IntermediatePhase 4 - Level 3: TransformationExample 8 of 10
rotate-right-by-1.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Rotate right
8if len(arr) > 0:
9 last = arr[-1]
10 for i in range(len(arr) - 1, 0, -1):
11 arr[i] = arr[i - 1]
12 arr[0] = last
13
14print(f"After right rotation: {arr}")

Output

Enter array size: 5
Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5
After right rotation: [5, 1, 2, 3, 4]

What's going on

Shift all elements right, move last to start.

Key Concepts:

Save last element
Shift all elements right
Place last at start