SDE & MLE Prep

142. Linked List Cycle II

Problem

Return the node where the cycle in a linked list begins, or null if there is no cycle. Don't modify the list.

Example: 3→2→0→-4 with the tail pointing back to 2 → the node 2

Constraints: follow-up: O(1) extra memory.

After slow and fast meet, restart one pointer at head; moving both one step at a time, they meet at the cycle entrance. (Distance head→entry ≡ distance meet→entry mod cycle length.)

head -> a -> b -> [c] -> d -> e
                   ^           |
                   +-----------+     x = head..c, meet inside; x ≡ meet..c

Complexity: O(n) time, O(1) space.

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
            if slow is fast:
                p = head
                while p is not slow:
                    p, slow = p.next, slow.next
                return p
        return None