LeetCode #61 Medium

Rotate List

Rotate a linked list to the right by k places.

linked-listtwo-pointers
Open on LeetCode ↗
02

Intuition

Rotating right by k just moves the last k nodes to the front — one cut, one splice. Close the list into a ring, walk to the new tail (position n − k%n − 1), and cut there. No node-by-node shuffling.

How to spot this pattern

Rotation is really "cut the list at a new place". Closing it into a ring first means you never juggle two loose ends — you just walk to the new tail and break there. Whenever a rotation problem gives you a linear structure, ask whether making it circular removes the special cases; it usually does.

03

Approach

1

Measure and normalize k

Walk once to get length n; k %= n since rotating by n is a no-op. If k becomes 0, return as-is.

2

Make it a ring

Point the old tail at the head. Now rotation is purely a question of where to cut.

3

Cut at the new tail

The new tail sits n − k − 1 steps from the old head. New head is its next; set tail.next = None.

04

Solution & live demo

1class Solution:
2 def rotateRight(self, head, k):
3 if not head or not head.next: return head
4 n, tail = 1, head
5 while tail.next:
6 tail = tail.next; n += 1
7 k %= n
8 if k == 0: return head
9 tail.next = head # close the ring
10 new_tail = head
11 for _ in range(n - k - 1):
12 new_tail = new_tail.next
13 new_head = new_tail.next
14 new_tail.next = None # cut
15 return new_head
05

Common pitfalls

Not reducing k modulo the length

✗ Wrong
for _ in range(k):
    # rotate one step
✓ Right
k %= n
if k == 0: return head

k can far exceed the list length — rotating a 3-node list 2,000,000 times is the same as rotating it twice. Without the modulo the loop runs k times, timing out on the exact inputs the problem is testing.

Counting the length off by one

✗ Wrong
n, tail = 0, head
while tail.next:
    tail = tail.next; n += 1
✓ Right
n, tail = 1, head
while tail.next:
    tail = tail.next; n += 1

The loop advances once per edge, not per node, so starting at 0 undercounts by one. That makes k % n wrong and the cut lands one position off.

Walking n - k steps to find the new tail

✗ Wrong
for _ in range(n - k):
    new_tail = new_tail.next
✓ Right
for _ in range(n - k - 1):
    new_tail = new_tail.next

Starting from head, taking n - k steps lands on the new head, one past the node you need to cut after. The new tail sits at index n - k - 1.

06

Edge cases

k ≥ n or k = 0

k %= n reduces both to the trivial case — return head unchanged.

Empty or single node

Early return; nothing to rotate.

07

Complexity

Time
O(n)
Space
O(1)
Two passes over the list.