Rotate List
Master this topic with zero to advance depth.
Rotate List
Rotate the list to the right by k places.
Visual Representation
1 -> 2 -> 3 -> 4 -> 5, k = 2
Output: 4 -> 5 -> 1 -> 2 -> 3Approach 1
Level III: Cycle + Break
Intuition
Form a cycle, find the new tail (n-k%n), and break.
⏱ O(N)💾 O(1)
Approach 2
Level II: Two Pointers
Intuition
Use two pointers, first and second. Move first k steps ahead. Then move both until first reaches the end. second will then be at the node before the new head.
⏱ O(N)💾 O(1)
Detailed Dry Run
1->2->3->4->5, k=2.
- First moves 2 steps to 3.
- Move both until First is at 5. Second is at 3.
- New head = 3.next = 4.
- 3.next = null, 5.next = head.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.