Skip to content
Decoder

Rotate List

Medium

Problem

You get the head of a linked list and a number k. Rotate the list to the right by `k` places: each rotation moves the last node to the front. Return the new head. Note that k can be much larger than the length of the list.

Example 1

Input
1
Output
2 -> 3 -> 4 -> 5, k = 2 → 4 -> 5 -> 1 -> 2 -> 3

Example 2

Input
0
Output
1 -> 2, k = 4 → 2 -> 0 -> 1

Example 3

Input
(empty), k = 3
Output
(empty)

Constraints

  • 0 <= number of nodes <= 500
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.