Orbital Shift: Rotate Array Right
๐ฆ Orbital Shift: Rotate Array Right
Difficulty: Beginner Tags: arrays, math, modulo, slicing Series: CS 102: Problem Solving & Logic
Problem
In the mystical orbital realm, elements shift positions in a circular pattern. Your task is to rotate an array to the right by k steps.
Given an array nums and an integer k, rotate the array to the right by k steps. Each step moves every element one position to the right, with the last element wrapping around to the front.
Real-World Application
Array rotation appears in: - Circular buffers - ring buffers in audio/video processing - Time series data - shifting time windows for analysis - Image processing - rotating pixel data for transformations - Cryptography - Caesar cipher implementations - Game development - cycling through inventory items - Scheduling algorithms - round-robin task scheduling - Data compression - Burrows-Wheeler transform preprocessing
Input
data = {
'nums': list[int], # Array to rotate
'k': int # Number of steps to rotate right
}
Output
list[int] # Rotated array
Constraints
- Array length โค 100,000
- k โฅ 0 (can be larger than array length)
- You may create a new array (in-place not required)
Examples
Example 1: Basic Rotation
Input: {'nums': [1,2,3,4,5,6,7], 'k': 3}
Output: [5,6,7,1,2,3,4]
Explanation: - Step 1: [7,1,2,3,4,5,6] - Step 2: [6,7,1,2,3,4,5] - Step 3: [5,6,7,1,2,3,4]
Or more simply: - Last 3 elements [5,6,7] move to front - First 4 elements [1,2,3,4] move to back
Example 2: k Larger Than Array Length
Input: {'nums': [1,2], 'k': 5}
Output: [2,1]
Explanation: - Array length = 2 - k = 5, so effective rotation = 5 % 2 = 1 - Rotate right by 1: [2,1]
Example 3: No Rotation
Input: {'nums': [1,2,3,4], 'k': 0}
Output: [1,2,3,4]
Explanation: - k = 0, no rotation needed
Example 4: Full Rotation
Input: {'nums': [1,2,3], 'k': 3}
Output: [1,2,3]
Explanation: - k = 3 = array length - Full rotation returns to original position
Example 5: Single Element
Input: {'nums': [1], 'k': 10}
Output: [1]
Explanation: - Single element array remains unchanged
Example 6: Empty Array
Input: {'nums': [], 'k': 5}
Output: []
Explanation: - Empty array remains empty
What You'll Learn
- Using modulo arithmetic to handle large k values
- Array slicing techniques in Python
- Understanding circular/cyclic operations
- The relationship between left and right rotations
Why This Matters
Array rotation is a classic interview problem that tests: - Index manipulation skills - Understanding of modulo arithmetic - Ability to optimize with mathematical insights - Edge case handling
Starter Code
def challenge_function(data):
"""
Rotate array to the right by k steps.
Args:
data: dict with keys:
- 'nums' (list[int]): array to rotate
- 'k' (int): number of steps to rotate right
Returns:
list[int]: rotated array
"""
# Your implementation here
pass