Skip to content

Loop in a Chain

Easy#fast-slow-pointers#cycle-detection~15 min

The mission

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

Target time
O(n)
Target space
O(1)

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

Python 3Ctrl+Enter runs