Rotate List
Given the head of a linked list, rotate it to the right by k places and return the new head. Rotating right by 1 moves the last node to the front; rotating by k moves the last k nodes to the front as a block, preserving their order. k can be far larger than the list length. Rewire in place. An empty or single-node list, and any k that is a multiple of the length, returns the list unchanged.
- The number of nodes is in the range [0, 500]
- -100 <= Node.val <= 100
- 0 <= k <= 2 × 10⁹
head = [1,2,3,4,5], k = 2[4,5,1,2,3]head = [0,1,2], k = 4[2,0,1]head = [1,2,3], k = 3[1,2,3]Rotating a linked list to the right by k places means the last k nodes move to the front, while their relative order remains unchanged. Essentially, we are picking a new starting point and severing the link that previously made the list linear.
A naive approach would be to perform k individual rotations. For each rotation, we find the second-to-last node, make the last node point to the current head, and then make the second-to-last node point to null. If k is very large (e.g., 2 billion), this approach is extremely inefficient (O(k * N)). We need a way to perform the rotation in a single pass regardless of k.
Instead of moving nodes one-by-one, we can think of the rotation as a single "cut" in a circle. If we connect the tail of the list back to the head, we create a Ring. In a ring, there is no beginning or end—we can choose any node to be the new head. Once we find our target, we simply "snap" the link behind it to turn the ring back into a linear list.
To locate the exact spot to "snap" the ring, we use the formula L - k - 1. Here is why: if we want to move the last k nodes to the front, the new tail must be the node that sits just before those k nodes. In a list of length L, the last k nodes start at position (L - k + 1). Therefore, the new tail is at position (L - k). Since we start our traversal at the head (index 0), we need to take (L - k - 1) steps to reach that new tail.
To perform this surgery, we manage three pointers: the Tail (scout that finds the end), the New Tail (the breakpoint), and the New Head (the new starting point).
# 1. Measure and Circle
curr, length = head, 1
while curr.next:
curr = curr.next
length += 1
curr.next = head # Ring created
# 2. Locate Cut (using L - k - 1 steps)
k %= length
steps_to_new_tail = length - k - 1
new_tail = head
for _ in range(steps_to_new_tail):
new_tail = new_tail.next
# 3. Snap
new_head = new_tail.next
new_tail.next = None
return new_headRing Persistence Manipulation
Phase Details
Phase 1: Measure & Modulo
Traverse the list to find length N. Compute effective rotation: `k = k % N`. If `k=0`, we stop.
We use k = k % length because rotating a list of length 5 by 7 steps is the same as rotating it by 2 steps.
Time Complexity: O(N) | Space Complexity: O(1). Converting to a circle simplifies complex head/tail shuffling.