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.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67k = int(input("Enter rotation count: "))8if arr:9 k = k % len(arr) # Handle k > n10 rotated = arr[-k:] + arr[:-k]11else:12 rotated = []1314print("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
If arr is nonempty, reduce k modulo its length.
- 2
Join the last k values with the preceding prefix.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum