DSA Factory
Free Linked lists lessonsLinked lists · Stage 4 · Harder rewiring · Step 4

Rotate the list

Move the last k nodes to the front by closing the chain into a ring, then cutting it at the right place. About 14 minutes.

Make it a ring

Rotating right by k moves the last k nodes to the front. In 1, 2, 3, 4, 5 with k equal to 2, the last two nodes, 4 and 5, go in front to give 4, 5, 1, 2, 3.

The trick: connect the last node back to the head to make a ring. A ring has no start, so the rotation is just a choice of where to cut it. The new tail is the node k places before the old end.

Tie tail to head: to make a ring.
Cut after the new tail, which is n minus k nodes from the head.
In code
tail.next = head   # the end meets the front
Rotate 6, 3, 8, 1, 5, 2, 7 right by 3.
6
0
3
1
8
2
1
3
5
4
2
5
7
6
cuttail

Walk to the end. The list has 7 nodes and the tail is node 7. k mod 7 is 3.

Move 1 of 4

Reduce k first

Rotating by the list length changes nothing, so use k modulo n. If the remainder is 0, return the list as it is.

Count the nodes on the way to finding the tail, so one walk gives you both n and the tail. An empty list or a one-node list is returned straight away, since division by n would otherwise fail.

Use k modulo n: so huge k is cheap.
Empty list: is returned as it is.
In code
k %= n
if k == 0:
    return head
Quick check

A list has 5 nodes and k is 12. How much do you rotate?

  1. ABy 2, since 12 mod 5 is 2
  2. BBy 12, one place at a time
  3. CNot at all
Show the answer

By 2, since 12 mod 5 is 2. After every 5 places the list returns to its start, so only the remainder matters.

Your problem

Rotate list

Given the head of a singly linked list and a non-negative integer k, rotate the list to the right by k places, so the last k nodes move to the front, and return the new head. If k is larger than the length, keep going around.

Example
head = [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3]

0 ≤ number of nodes ≤ 5,000 · 0 ≤ k ≤ 2,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve