Coding Interview PatternsRotate List
MediumFast and Slow Pointers
Rotate List
Explanation & Solution
Description
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
0
1
1
2
2
3
3
4
4
5
Output:[4,5,1,2,3]
0
4
1
5
2
1
3
2
4
3
Explanation: After rotating right by 1: [5,1,2,3,4]. After rotating right by 2: [4,5,1,2,3].
Constraints
- The number of nodes in the list is in the range
[0, 500] -100 <= Node.val <= 1000 <= k <= 2 * 10⁹
Approach
Fast and Slow Pointers pattern
1. Handle Edge Cases
- If the list is empty, has only one node, or
kis 0, return the list as-is.
2. Find the Length and Tail
- Traverse the list to find its total
lengthand a reference to thetailnode.
3. Normalize k
- Compute
k = k % lengthto handle cases wherekis larger than the list length. - If
kbecomes 0 after normalization, the list stays unchanged — return it directly.
4. Make the List Circular
- Connect
tail.next = headto form a circular linked list.
5. Find the New Tail
- The new tail is at position
length - k - 1from the original head. - Walk
length - k - 1steps fromheadto reach it. - The node right after the new tail becomes the new head.
6. Break the Circle
- Set
newTail.next = nullto break the circular connection. - Return the result starting from
newHead.
Key Insight
- Rotating right by
kis equivalent to taking the lastknodes and moving them to the front. - Making the list circular simplifies the pointer manipulation — we only need to find where to "cut".
Time
O(n)two passes through the list at most.Space
O(1)only a few pointer variables are used (excluding the output array).Visualization
Input:
Linked List Traversal
—
Press play to start traversal
Slow (S)Fast (F)Both
8 steps