Rotate Array by K Positions

Rotate array elements by k positions to the right.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 12 of 14
rotate-array-by-k-positions.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
7k = int(input("Enter rotation count: "))
8k = k % n # Handle k > n
9
10# Rotate
11rotated = arr[-k:] + arr[:-k]
12
13print("Rotated array:", rotated)

Output

Enter array size: 5
Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5
Enter rotation count: 2
Rotated array: [4, 5, 1, 2, 3]

What's going on

Use slicing to rotate array.

Key Concepts:

Take last k elements
Take first n-k elements
Concatenate in rotated order