← DiffPush

Detect loop in LL

Standard Bar Linked List · Medium Problems of LL O(N) · O(1)

Two Runners on a Possibly Circular Track

A conveyor's return path may have been wrongly coupled back onto itself somewhere in the middle, creating a loop that would spin any single scanner forever. The inspection rig deploys two probes that travel at different speeds; on a straight run the faster probe escapes to the end, but on a loop it must eventually overtake the slower one. Report whether the belt is looped.

Input: An array head of node values and an integer pos — the 0-based index the tail's next pointer connects to, or -1 when there is no loop.

Output: true when the list contains a cycle, false otherwise.

Constraints

Examples

Example 1

Input: {"head":[3,2,0,-4],"pos":1}
Output: true
The tail reconnects to the node holding 2, closing a loop.

Example 2

Input: {"head":[1,2],"pos":0}
Output: true
The tail connects back to the head — the whole list is one loop.

Solve this in your browser →

Also on LeetCode ↗