‹ DS&A interview · Socratic
DSA · Linked List · #156

Rotate List

Module 42 · difficulty 3/5·30:00starts on first keystroke

Given the `head` of a singly linked list, rotate the list to the right by `k` places. Rotating to the right by one moves the last node to the front. Implement `rotateRight(head, k)` and return the new head of the rotated list. `k` may be larger than the list length, so rotations wrap around (only `k mod length` rotations have any effect).

Examples
  • head = [1,2,3,4,5], k = 2 [4,5,1,2,3]Move the last 2 nodes (4,5) to the front.
  • head = [0,1,2], k = 4 [2,0,1]k=4 with length 3 is equivalent to k=1.
  • head = [], k = 5 []Empty list stays empty.
Constraints
  • · The number of nodes in the list is in the range [0, 500].
  • · -100 <= Node.val <= 100
  • · 0 <= k <= 2 * 10^9
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.