Shift a playlist k places to the right, in place

Arrays, strings and hash maps Mid-level Python 3.13+ Reviewed By Best Latest Apps

Order the steps

Put the in-place right shift in order.

  • Replace k with k % n (stop if n is 0)
  • Reverse the first k items
  • Reverse the whole list
  • Reverse the remaining n - k items

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A C B D

  1. Replace k with k % n (stop if n is 0) Large k wraps around; this must come first.
  2. Reverse the whole list The last k items move to the front, in reverse order.
  3. Reverse the first k items Restores the order of the moved block.
  4. Reverse the remaining n - k items Restores the order of the rest.

30-second answer

Reduce k modulo the length, then reverse the whole list, reverse the first k songs and reverse the rest. Three in-place reversals give the shifted order with O(n) time and O(1) extra space. Slicing (songs[-k:] + songs[:-k]) is shorter but builds a new list.

Practise saying it · 45 s. No recording, just a timer

Explain the three-reversal shift.

Say your answer out loud, then check which of these points you covered:

  • k % n first
  • Three reversals
  • O(1) extra space

Deep dive

Reversing everything puts the last k songs at the front, but backwards; the two smaller reversals fix the order inside each part.

k % n handles k larger than the list and k equal to it (no change). Guard n = 0 first.

A cycle-following method also works in O(1) space but is easier to get wrong under pressure.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def shift_right(songs: list[int], k: int) -> list[int]:
    n = len(songs)
    if n == 0:
        return songs
    k %= n

    def flip(lo: int, hi: int) -> None:
        while lo < hi:
            songs[lo], songs[hi] = songs[hi], songs[lo]
            lo, hi = lo + 1, hi - 1

    flip(0, n - 1)
    flip(0, k - 1)
    flip(k, n - 1)
    return songs

Common mistakes

  • Skipping k %= n, which indexes past the end when k > n.
  • Assigning songs = songs[-k:] + songs[:-k] inside a function, which rebinds a local name and leaves the caller's list unchanged.

Senior take & follow-ups

Mention the slicing one-liner and why the in-place version is asked: memory, and mutating the caller's list.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you shift left instead?

    Show hint

    Shift right by n - k, or reverse the first k, the rest, then the whole list.

  2. What about a linked list?

    Show hint

    Find the new tail at n - k - 1, cut there and join the old tail to the old head.

What each operation costs: Arrays · Dynamic Arrays · Hash Table · Hash Functions

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.