Rotate List - Problem
You're given the head of a singly linked list, and your task is to rotate the list to the right by k places.
What does rotation mean? Rotating a linked list to the right by k places means taking the last k nodes from the end and moving them to the front of the list.
Example:
- Original list:
1 → 2 → 3 → 4 → 5 - Rotate right by 2:
4 → 5 → 1 → 2 → 3
The challenge is to handle this efficiently without creating a new list, and to deal with edge cases like when k is larger than the list length.
Input & Output
example_1.py — Basic Rotation
$
Input:
head = [1,2,3,4,5], k = 2
›
Output:
[4,5,1,2,3]
💡 Note:
We rotate the list to the right by 2 places. The last 2 nodes (4,5) move to the front, and the rest (1,2,3) move to the back.
example_2.py — Single Rotation
$
Input:
head = [0,1,2], k = 4
›
Output:
[2,0,1]
💡 Note:
Since k=4 and list length is 3, we effectively rotate by 4%3=1 position. Only the last node (2) moves to the front.
example_3.py — Edge Case
$
Input:
head = [1], k = 1
›
Output:
[1]
💡 Note:
With only one node, any rotation returns the same list since there's nowhere to move the node to.
Constraints
- The number of nodes in the list is in the range [0, 500]
- Each node's value is in the range [-100, 100]
- 0 ≤ k ≤ 2 × 109
- k can be much larger than the list length
Visualization
Tap to expand
Understanding the Visualization
1
Form a Circle
Connect the last person to the first to form a circle
2
Count and Calculate
Count total people and calculate effective rotation (k % total)
3
Find Break Point
Walk (total - k) steps from the original start to find where to break
4
Break and Reform
Break the circle at the calculated point to get the new arrangement
Key Takeaway
🎯 Key Insight: Converting to a circular list eliminates the need for multiple traversals and naturally handles the modulo arithmetic for large k values.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code