61 - Rotate List
Friday, 18 September 2026
<medium> [problem]
Rotating right by k only moves the cut, not the nodes, so open a gap of k between two pointers and walk them together until the front one lands on the tail.
{linked list}{two pointers}
Problem
Given the head of a linked list, rotate the list to the right by k places.
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Input: head = [0,1,2], k = 4
Output: [2,0,1] Constraints:
- The number of nodes is in the range
[0, 500] -100 <= Node.val <= 1000 <= k <= 2 * 10^9
Approach
Rotating doesn’t reorder anything. The sequence 1 2 3 4 5 rotated right by two is 4 5 1 2 3 —
the same cyclic order, read starting from a different place. So treat the list as a ring and the job
is just picking where to cut it:
1 -> 2 -> 3 -> 4 -> 5 -+ rotate right by 2
^----------------------+ cut here: between 3 and 4
new head = index n - k = 3 new tail = index n - k - 1 = 2 class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head == nullptr) return nullptr;
ListNode* curr = head;
int nodes = 0;
while (curr) {
nodes++;
curr = curr->next;
}
k %= nodes;
if(k == 0) return head;
ListNode *slow = head, *fast = head;
while (k--) {
fast = fast->next;
}
while (fast->next) {
slow = slow->next;
fast = fast->next;
}
fast->next = head;
head = slow->next;
slow->next = nullptr;
return head;
}
}; - time:
O(n)- one pass to count, one to walk the pair - space:
O(1)- two pointers, nodes relinked in place