Skip to content
BytePatterns

Loop in a Chain

EasyLinked Lists#fast-slow-pointers#cycle-detection~15m

Problem

You receive the head of a singly linked chain of nodes. Somewhere a node may point back to an earlier node, which makes the walk go round forever instead of reaching the end. Return True if the chain contains such a loop and False if following the links eventually reaches None. In the examples the chain is described by its values plus pos, the index the last node links back to, or -1 for no loop.

Examples

Input:  values = [3, 2, 0, -4], pos = 1
Output: True
Why:    the last node links back to the node holding 2
Input:  values = [1, 2], pos = -1
Output: False
Why:    the walk ends after the second node
Input:  values = [7], pos = 0
Output: True
Why:    edge case, a single node that points to itself

Hints

0 / 3

Stuck on the idea rather than the code? Detect a Cycle covers it.