Rotate List - Problem
Given the head of a linked list, rotate the list to the right by k places.
When we rotate to the right by k places, the last k nodes from the end become the first k nodes at the beginning, and the remaining nodes shift to the right.
Example: If we have list 1→2→3→4→5 and rotate by 2 places, the result is 4→5→1→2→3. The last 2 nodes (4,5) moved to the front.
Input & Output
Example 1 — Basic Rotation
$
Input:
head = [1,2,3,4,5], k = 2
›
Output:
[4,5,1,2,3]
💡 Note:
Rotating right by 2 means the last 2 nodes (4,5) move to the front: 1→2→3→4→5 becomes 4→5→1→2→3
Example 2 — Single Rotation
$
Input:
head = [0,1,2], k = 4
›
Output:
[2,0,1]
💡 Note:
k=4 with length=3, so effective rotation is 4%3=1. Move last node to front: 0→1→2 becomes 2→0→1
Example 3 — No Rotation Needed
$
Input:
head = [1], k = 1
›
Output:
[1]
💡 Note:
Single node list remains unchanged regardless of k value
Constraints
- The number of nodes in the list is in the range [0, 500]
- -100 ≤ Node.val ≤ 100
- 0 ≤ k ≤ 2×109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original linked list: 1→2→3→4→5, k=2
2
Process
Last k=2 nodes move to front
3
Output
Rotated list: 4→5→1→2→3
Key Takeaway
🎯 Key Insight: Making the list circular first allows us to rotate efficiently in O(n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code