SDE & MLE Prep

61. Rotate List

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