Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Rotate Array by K Positions

Rotate a list right by k positions using slices. Students normalize the count, join the wrapped suffix and prefix, and handle zero-sized input before modulo.

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: "))
8if arr:
9 k = k % len(arr) # Handle k > n
10 rotated = arr[-k:] + arr[:-k]
11else:
12 rotated = []
13
14print("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]

In this one

  • Normalize rotations
  • Join wrapped slices
  • Guard an empty divisor

How it works

  1. 1

    If arr is nonempty, reduce k modulo its length.

  2. 2

    Join the last k values with the preceding prefix.

  3. 3

    Otherwise return an empty rotated list.

Edge cases

What if k exceeds the length?

What if k exceeds the length?

Modulo keeps only the effective rotation count.

What if the list is empty?

What if the list is empty?

It should return an empty rotation without evaluating k % 0.

What's going on

For a nonempty list, k % n reduces full rotations. arr[-k:] supplies the suffix that wraps to the front, followed by arr[:-k].

For [1, 2, 3, 4] and k equal to one, the result is [4, 1, 2, 3]. k equal to zero also works with these slices. Empty input needs a guard before modulo because its size is zero.

What if k exceeds the length? Modulo keeps only the effective rotation count.

What if the list is empty? It should return an empty rotation without evaluating k % 0.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Does this change arr in place?

Pick an answer to check it.

Question 2

What if k exceeds the length?

Pick an answer to check it.

Questions people ask

What if k exceeds the length?

Modulo keeps only the effective rotation count.

What if the list is empty?

It should return an empty rotation without evaluating k % 0.

Does this change arr in place?

No, it creates rotated.