Move the last K nodes to the front of the linked list. Β β± Time
O(n)Β πΎ SpaceO(1)
- Find the length and the tail of the list.
- Handle
k % length(rotating by full length = no-op). - Make the list circular (tail.next = head).
- Walk
length - ksteps from the tail to find the new tail. - Set
new_head = new_tail.nextand break the circle.
Algorithm:
length = 1; tail = head
while tail.next: tail = tail.next; length++
k = k % length
if k == 0: return head
tail.next = head β make circular
steps = length - k
new_tail = tail
for _ in range(steps): new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None
return new_head
List: 1 β 2 β 3 β 4 β 5, k = 2
Length = 5, k % 5 = 2
Make circular: 1 β 2 β 3 β 4 β 5 β (back to 1)
New tail is at position: 5 - 2 = 3 steps from tail
Walk 3 steps from tail (5): 5β1β2β3
New tail = 3, New head = 4
Break circle: 3.next = None
Result: 4 β 5 β 1 β 2 β 3 β
(last 2 elements moved to front)
Linked list rotation is LeetCode 61. The circular-list trick avoids special-casing the reconnection and is an elegant example of how temporary modification of a data structure can simplify algorithm logic.
- Always handle k % length β rotating by length is a no-op, and k can be larger than length
- The
length - kformula: we want the last k nodes at the front, so the new tail is at positionlength - k - Make the list circular temporarily β cleaner than tracking multiple pointers
- Edge cases:
head == None,k == 0, single element, k is a multiple of length - Follow-up: what if k is negative (left rotation)?
k = length - (abs(k) % length)
- Circular buffer / ring buffer management
- Round-robin scheduling (rotate the queue each time slot)
- Caesar cipher key rotation
- Token ring network protocols
- Reverse Linked List β pointer manipulation on linked lists
- Detect Cycle Linked List β cycle detection
- Merge K Lists β linked list operations