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.

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

python
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

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.

06

Complexity

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