Find the duplicate number
- CH1 slow
- CH2 fast
Each value links to an index. Where the loop starts, two links meet: that index is the duplicate.
Step through it →Two pointers follow the same links, one twice as fast. If the links loop, the fast one catches the slow one; if not, it reaches the end first.
Each step moves slow one link and fast two. Once both are in the loop, fast gains exactly one link a step, so it can't jump over slow. It lands on slow within one lap.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
Comparing slow and fast before moving them says True at once, since both start at the head. And checking only fast before fast.next.next crashes on the last node.
Each value links to an index. Where the loop starts, two links meet: that index is the duplicate.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
def has_cycle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: return True return False