Skip to main content
medium

Rotate Array

Spin a playlist. One spin moves the last song to the front and slides every other song back by one place. Spin k times in all, then return the playlist as it ends up. k can be 0, and it can be far larger than the playlist itself. Limits: 1 to 500,000 songs, each id from -1,000,000,000 to 1,000,000,000; k from 0 to 2,147,483,647. Think about: what does a playlist of 5 songs look like after exactly 5 spins? Example (playlist 8, 3, 5, 9, 2 with k = 2): spin 1: the last song, 2, jumps to the front => 2, 8, 3, 5, 9 spin 2: the last song, 9, jumps to the front => 9, 2, 8, 3, 5 full answer: [9, 2, 8, 3, 5] with k = 7 the answer is the same: five spins bring the playlist back to where it started

You're spinning a playlist: each spin moves the last song to the front, and you spin k times. Interviewers like it because the obvious move, one step at a time, gets painfully slow when k is huge. The classic trap is a k bigger than the playlist, where a full lap changes nothing. You get 1 to 500,000 song ids from -1,000,000,000 to 1,000,000,000, and k can be anything from 0 to 2,147,483,647.

Examples

You write

rotate_array(nums: List[int], k: int)

  1. Example 1

    Input
    nums = [8,3,5,9,2], k = 2
    returns
    [9,2,8,3,5]
  2. Example 2

    Input
    nums = [4,7,1], k = 0
    returns
    [4,7,1]

Save this for your laptop

The editor and Run need a bigger screen. The link opens Rotate Array ready to code. It is free, and the editor needs no account.

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 126 Arrays & Hashing problems

Two Pointers

I reach for it when

  • The array is sorted, or you can sort it.
  • You need a pair, a triple or a palindrome.

Say this before you type. Say what each pointer means and what a move to the left or right rules out.

All 26 Two Pointers problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.

1Rotate Arraymedium
Based onLeetCode

Get a note when something new lands

New company guides, new problems and big changes to Coco. Rare, and you can leave any time. By joining you agree to get these emails.