py_twist_sequence — Rotate an Array Right by K
Difficulty: medium
Write a function that rotates an array to the right by k positions. Rotating right by k means the last k elements move to the front. k may be larger than the array length.
def twist_sequence(arr: list[int], k: int) -> list[int]:
Examples
>>> twist_sequence([1, 2, 3, 4, 5], 2)
[4, 5, 1, 2, 3]
>>> twist_sequence([1, 2, 3], 1)
[3, 1, 2]
>>> twist_sequence([1, 2, 3, 4], 0)
[1, 2, 3, 4]
>>> twist_sequence([1, 2, 3], 5)
[2, 3, 1]
>>> twist_sequence([], 3)
[]
Solution
Download py_twist_sequence.pydef twist_sequence(arr: list[int], k: int) -> list[int]:
if not arr:
return []
k = k % len(arr)
if k == 0:
return arr[:]
return arr[-k:] + arr[:-k]
How It Works
Goal: Move the last k elements of the array to the front, with k possibly exceeding the array length.
Approach: Reduce k modulo the array length, then build the result with two slices: the tail of length k followed by everything else.
Step by step:
- Empty array returns an empty list immediately.
k = k % len(arr)normalizesk— rotating bylen(arr)is the same as no rotation.- If
k == 0, return a copy of the original (slicing avoids aliasing the caller's list). arr[-k:]is the lastkelements;arr[:-k]is the rest. Concatenating gives the rotated array.
Key concept: Slicing as rotation — Python's expressive slice syntax turns array rotation into one line, no swaps or modular index arithmetic needed.