Implement cycle detection using the fast-slow pointer technique. Here's the trick: in a cycle, fast catches up to slow at a rate of one node per iteration.
They must meet within one full cycle. At most steps.
Edge cases to handle:
- Empty list (head is null)
- Single node with no cycle
- Single node pointing to itself
- Cycle at the head vs. cycle in the middle
The beauty of this algorithm is its simplicity. The same code handles all cases. Time: . Space: .