Given the head of a singly linked list, determine whether the list contains a cycle.
A cycle exists when a node's next pointer points to a previous node in the list, creating a loop.
head = [3, 2, 0, -4]
pos = 1
┌──────────────────┐
↓ │
3 → 2 → 0 → -4 ──────┘
index 1
We use two pointers:
slow: moves one node at a time.fast: moves two nodes at a time.Why does this work?
fast eventually reaches None.fast eventually catches up with slow inside the cycle.fast and slow point to the same node, a cycle exists.Think of two runners on a circular track: the faster runner eventually catches the slower runner.
We want to achieve:
O(n) — each pointer traverses at most a linear number of nodes.O(1) — we only need two pointers.