Skip to main content

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.py
def 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:

  1. Empty array returns an empty list immediately.
  2. k = k % len(arr) normalizes k — rotating by len(arr) is the same as no rotation.
  3. If k == 0, return a copy of the original (slicing avoids aliasing the caller's list).
  4. arr[-k:] is the last k elements; 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.