SDE & MLE Prep

141. Linked List Cycle

Problem

Decide whether a linked list contains a cycle, i.e. following next pointers eventually revisits a node.

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

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

Floyd: slow moves 1, fast moves 2. If there's a cycle they must meet; otherwise fast hits null.

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

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
            if slow is fast:
                return True
        return False