Rotate List (LeetCode 61): Solution and Explanation
Given the head of a 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 in order. The value of k can be much larger than the length of the list.
Watch it run step by step
Try your own input and write the code →Intuition
A literal approach rotates one step at a time: find the last node, detach it, and put it in front of the head, then repeat k times. Each single rotation costs O(n) to find the tail, so this is O(n × k), and with k as large as two billion it never finishes.
Two observations fix this. First, rotating a list of length n by n places brings it back to where it started, so only k % n matters. That immediately caps the work. Second, a rotation by k does not need to move nodes one by one at all. The result is just the same chain of nodes cut at a different place: the last k nodes become the front, and the first n - k nodes follow them. In a linked list, cutting and rejoining a chain takes only a couple of pointer changes.
So the plan is to find the length and the tail in one pass, reduce k, and if it is nonzero, walk to the node that will become the new tail, which is at position n - k counting from 1. The node after it is the new head. Break the chain after the new tail, then attach the old tail to the old head. Everything is constant work except the two walks, so the whole rotation is linear and uses no extra memory.
Approach: Measure, reduce k, and relink
- Return
headunchanged if the list is empty, has one node, ork == 0. - Walk from
headto the last node, countinglengthand keeping a reference totail. - Reduce
k = k % length; if it becomes 0, the rotation is a no-op, so returnhead. - Starting at
head, step forwardlength - k - 1times to reachnew_tail, the node that will end the rotated list. - Set
new_head = new_tail.next, then cut the chain withnew_tail.next = None. - Link
tail.next = headto put the original front after the moved block, and returnnew_head.
Step-by-step example
head = [1, 2, 3, 4, 5], k = 2
- The length walk ends at node 5, so
length = 5andtailis node 5. k % 5is 2, so the rotation is real.- Step
5 - 2 - 1 = 2times from the head: 1 to 2, then 2 to 3.new_tailis node 3. new_headis node 4. Setting3.next = Nonesplits the list into [1, 2, 3] and [4, 5].- Linking
5.next = 1joins them as 4, 5, 1, 2, 3, and the function returns node 4.
Code: Python, Java, C++
1class Solution:
2 def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
3 if not head or not head.next or k == 0:
4 return head
5
6 # Find length and tail
7 length = 1
8 tail = head
9 while tail.next:
10 tail = tail.next
11 length += 1
12
13 # Calculate actual rotation
14 k = k % length
15 if k == 0:
16 return head
17
18 # Find new tail
19 new_tail = head
20 for _ in range(length - k - 1):
21 new_tail = new_tail.next
22
23 # Rotate
24 new_head = new_tail.next
25 new_tail.next = None
26 tail.next = head
27
28 return new_head1class Solution {
2 public ListNode rotateRight(ListNode head, int k) {
3 if (head == null || head.next == null || k == 0) return head;
4
5 // Find length and tail
6 int length = 1;
7 ListNode tail = head;
8 while (tail.next != null) {
9 tail = tail.next;
10 length++;
11 }
12
13 // Calculate actual rotation
14 k = k % length;
15 if (k == 0) return head;
16
17 // Find new tail (length - k - 1 steps from head)
18 ListNode newTail = head;
19 for (int i = 0; i < length - k - 1; i++) {
20 newTail = newTail.next;
21 }
22
23 // Rotate
24 ListNode newHead = newTail.next;
25 newTail.next = null;
26 tail.next = head;
27
28 return newHead;
29 }
30}1class Solution {
2public:
3 ListNode* rotateRight(ListNode* head, int k) {
4 if (!head || !head->next || k == 0) return head;
5
6 // Find length and tail
7 int length = 1;
8 ListNode* tail = head;
9 while (tail->next) {
10 tail = tail->next;
11 length++;
12 }
13
14 // Calculate actual rotation
15 k = k % length;
16 if (k == 0) return head;
17
18 // Find new tail
19 ListNode* newTail = head;
20 for (int i = 0; i < length - k - 1; i++) {
21 newTail = newTail->next;
22 }
23
24 // Rotate
25 ListNode* newHead = newTail->next;
26 newTail->next = nullptr;
27 tail->next = head;
28
29 return newHead;
30 }
31};Time and space complexity
O(n)
One full pass measures the length and finds the tail, and a second partial pass of at most n - 1 steps finds the new tail. The size of k no longer matters after the modulo.
O(1)
Only a few node references and counters are used. The rotation reuses the existing nodes.
Other approaches
Close into a ring, then break (time O(n), space O(1))
After finding the tail, link it to the head to form a cycle, walk length - k steps from the old tail to the new tail, and break the ring there. It is the same work with slightly different bookkeeping, and some people find it easier to get the step count right.
Rotate one step at a time (time O(n × min(k, n)), space O(1))
Repeat k times: find the second-to-last node, detach the last node, and make it the new head. It is easy to understand but costs O(n) per step, so it is only practical after reducing k modulo the length, and even then it is quadratic in the worst case.
Common mistakes
- Skipping the modulo. Without
k % length, a hugekmakes any step-based approach time out, and the walk countlength - k - 1goes negative. - Starting the length counter at 0 while starting the walk at
head. The reference code starts at 1 because the head itself is already counted. - Walking
length - ksteps instead oflength - k - 1. That lands on the new head rather than the node before it, so you cannot cut the chain. - Forgetting
new_tail.next = None. The list becomes a cycle and any traversal of the result never terminates.
Frequently asked questions
Why use k modulo the length in Rotate List?
Rotating by the full length returns the list to its original order, so rotations repeat every length steps. Taking k % length keeps only the rotation that actually changes anything.
How do you find the new head after rotating right by k?
The new head is the node at position length - k counting from 0, which is the first of the last k nodes. You reach it by stepping to the node just before it and reading its next.
Is rotating a linked list easier than rotating an array?
In one sense, yes. A list rotation is just a cut and a reconnection with O(1) pointer changes, while an array rotation must move every element, typically with the triple-reverse trick.