InterviewPrepKit

Home / Coding / Linked List

Rotate List

medium Original β†—
Solving tips
  • First reduce k modulo n (k can be up to ~2e9); if k % n == 0 it's a no-op, return head unchanged.
  • The cleanest trick: close the list into a ring by linking tail to head, then walk to the new tail and break it.
  • The new tail sits at index n-k-1 (0-based), so from the head take exactly n-k-1 .next steps; be careful with this off-by-one.
  • Handle empty/single-node lists up front; target O(n) time and O(1) space, and never return a still-cyclic list.

Problem

You are given the head of a singly linked list and an integer k. Rotate the list to the right by k places. Rotating right by one takes the last node and moves it to the front; doing this k times shifts every node k positions toward the tail, with nodes that fall off the end wrapping around to the front.

Return the head of the rotated list.

k can be much larger than the length of the list, so rotating by k is the same as rotating by k mod n, where n is the number of nodes.

Examples

Example 1

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Rotate right once β†’ [5,1,2,3,4]; a second time β†’ [4,5,1,2,3].

Example 2

Input: head = [0,1,2], k = 4
Output: [2,0,1]

n = 3, and 4 mod 3 = 1, so this is a single right rotation: the last node 2 moves to the front.

Example 3

Input: head = [], k = 5
Output: []

An empty list (or a single-node list) is unchanged by any rotation.

Constraints

  • The number of nodes is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9 β€” so k may vastly exceed the list length; always reduce it modulo n.

Think about it first

Hint 1 Rotating right by k moves the last k nodes to the front. Which single node becomes the new head, and which node becomes the new tail?
Hint 2 First find the length n (one pass). Rotating by k is the same as rotating by k mod n. The new tail is the node at index n - k - 1 (0-based); the node right after it becomes the new head.
Hint 3 A clean trick: connect the tail to the head to form a ring, then walk forward to the new tail and break the ring there. The break point is n - (k mod n) steps from the original head.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.