Rotate List
The key idea
Rotating right by
k only moves the last k % len nodes to the front. Close the list into a ring, then re-open it k % len steps before the old tail so the new head and new tail fall in the right place.Problem
Given the head of a linked list, rotate the list to the right by k places.
Each rotation moves the last node of the list to the front. Doing this k times shifts every node k positions to the right, and the nodes that fall off the end wrap around to the beginning. Because rotating by the list's length n returns the original list, only k % n actually matters.
Constraints
- The number of nodes in the list is in the range
[0, 500]. -100 <= Node.val <= 1000 <= k <= 2 * 10^9
Examples
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]
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Linked List problems
- Add Two NumbersMEDIUM
- Copy List with Random PointerMEDIUM
- Design Linked ListMEDIUM
- Insert Greatest Common Divisors in Linked ListMEDIUM
- Intersection of Two Linked ListsEASY
- Maximum Twin Sum of a Linked ListMEDIUM
- Merge Two Sorted ListsEASY
- Odd Even Linked ListMEDIUM
- Partition ListMEDIUM
- Remove Duplicates from Sorted List IIMEDIUM
- Remove Linked List ElementsEASY
- Remove Nth Node From End of ListMEDIUM