Skip to content
BytePatterns

Where the Loop Begins

MediumLinked Lists#fast-slow-pointers#cycle-detection~30m

Problem

You receive the head of a singly linked chain that may end in a loop, where the last node links back to an earlier one. Return the first node of the loop, the one you reach first when walking from the head, or None if the chain has no loop. Use O(1) extra memory and do not change any links. In the examples the chain is given by its values plus pos, the index the last node links back to, or -1 for no loop, and the output shows the value of the returned node.

Examples

Input:  values = [3, 2, 0, -4], pos = 1
Output: 2
Why:    the walk enters the loop at the node holding 2
Input:  values = [1, 2], pos = 0
Output: 1
Why:    the whole chain is the loop, so it starts at the head
Input:  values = [1], pos = -1
Output: None
Why:    edge case, no loop to enter

Hints

0 / 3

Stuck on the idea rather than the code? Find the Cycle Start covers it.