How to Rotate an Array by k Steps in Python
This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.
Python code
13 linesdef rotate_array(nums, k):
if not nums:
return []
n = len(nums)
k = k % n
return nums[-k:] + nums[:-k] if k else nums[:]
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6]
k = 2
result = rotate_array(arr, k)
print(f"Original: {arr}")
print(f"Rotated by {k}: {result}")
Output
Original: [1, 2, 3, 4, 5, 6]
Rotated by 2: [5, 6, 1, 2, 3, 4]
How it works
The function first checks for an empty list and returns an empty list as a safety guard. It then normalizes k using the modulo operator k % n, because rotating by more than the list length wraps around. The return statement uses slicing: nums[-k:] extracts the last k elements, and nums[:-k] gets the rest, then concatenates them to form the rotated list. If k becomes zero (meaning the rotation is a full cycle back to the original), it returns a copy of the original list to avoid mutating the caller's data.
Common mistakes
- Forgetting to handle k larger than the list length without modulo
- Overlooking the empty list case causing an index error
- Mutating the original list unexpectedly rather than returning a new one
Variations
- Use `collections.deque` with `rotate(k)` for in-place rotation
- Implement a three-step reverse in-place rotation for O(1) extra space
Real-world use cases
- Rotating log files or time-series data for efficient sliding-window analysis.
- Cycling through queue items in a round-robin load balancer process.
- Implementing a rotating buffer in embedded systems for sensor data processing.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.