61. Rotate List
Asked at 10Bloomberg54Amazon50Google44Microsoft40Meta36Airwallex100Nvidia60josh technology58LinkedIn45Oracle41
Problem
Rotate a linked list to the right by k places: the last k nodes move to the front.
Example: 1→2→3→4→5, k = 2 → 4→5→1→2→3; 0→1→2, k = 4 → 2→0→1
Constraints: k up to 2·10⁹.
Find the length and tail; connect tail → head to form a ring; the new tail is n − k % n − 1 steps from the head; break the ring after it.
Complexity: O(n).
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head:
return None
n, tail = 1, head
while tail.next:
tail, n = tail.next, n + 1
tail.next = head # ring
for _ in range(n - k % n - 1):
head = head.next
new_head, head.next = head.next, None
return new_head
assert list_vals(Solution().rotateRight(make_list([1, 2, 3, 4, 5]), 2)) == [4, 5, 1, 2, 3]
assert list_vals(Solution().rotateRight(make_list([0, 1, 2]), 4)) == [2, 0, 1]
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return null;
int n = 1;
ListNode tail = head;
while (tail.next != null) { tail = tail.next; n++; }
tail.next = head;
ListNode newTail = head;
for (int i = 0; i < n - k % n - 1; i++) newTail = newTail.next;
ListNode newHead = newTail.next;
newTail.next = null;
return newHead;
}
}
func rotateRight(head *ListNode, k int) *ListNode {
if head == nil {
return nil
}
n, tail := 1, head
for tail.Next != nil {
tail, n = tail.Next, n+1
}
tail.Next = head // close the ring, then cut it n - k%n nodes in
for i := 0; i < n-k%n-1; i++ {
head = head.Next
}
newHead := head.Next
head.Next = nil
return newHead
}