Rotate a Linked List

medium

You are given the head of a singly linked list and an integer k. Left rotate the list k times and return the new head.

A single left rotation moves the first node to the back: 10 → 20 → 30 becomes 20 → 30 → 10. Do this k times in total.

Note that k can be far larger than the length of the list — rotating a list of n nodes exactly n times leaves it unchanged, so only k mod n rotations actually matter.

Hints

Rotating the list a full length's worth of times leaves it exactly as it started — what does that tell you about a huge k?
A left rotation by k is really one cut: the first k nodes move, as a block, to the very end.
Find the length and the tail in one walk, reduce k with k % n, then step to the node at index k-1 and relink three pointers.

Common doubts

Because k can be as large as 10^9. Every n rotations returns the list to its original order, so only k % n rotations actually change anything.
Nothing should move — return the original head. Skipping this check risks stepping past the end or breaking the list.

Interview follow-ups

A right rotation by k equals a left rotation by n - (k % n). Reduce, convert, and reuse the same cut-and-splice.
You still need n to reduce k, but you can avoid a second walk: connect the tail to the head to form a ring, then advance n - k steps and break the ring there.

Fun facts

  • The same cut-at-index-k trick rotates arrays in place using three reversals — a favorite interview follow-up.
  • Circular buffers use exactly this idea: rotation is just moving where you consider the 'start' to be, no data actually shifts.

Asked at

AmazonMicrosoftAdobeGoogle
Frequently Sometimes Occasionally
Example 1
Input: head = [10,20,30,40,50], k = 4
Output: [50,10,20,30,40]
Rotate 1: 20 30 40 50 10; Rotate 2: 30 40 50 10 20; Rotate 3: 40 50 10 20 30; Rotate 4: 50 10 20 30 40.
Example 2
Input: head = [10,20,30,40], k = 6
Output: [30,40,10,20]
With n = 4, k = 6 behaves like k = 2, so the first two nodes move to the back.
Constraints

- 1 <= number of nodes <= 10^5 - 0 <= k <= 10^9 - 0 <= node.data <= 10^9

Solve this problem →