InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Rotate List

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug