CodeArchon

easyLinked ListAmazonMicrosoft

Loop Detector

Audit a linked chain for a hidden feedback loop. Report whether any node is reachable from itself.

Given the head of a linked list, decide whether the list contains a cycle. Use O(1) extra space.

Choose approach

3
slowfast
2
0
-4
1/5
Narrationstep 1 of 5

slow + fast both start at head. slow steps 1 node, fast steps 2 nodes. They meet inside a cycle.

1def loop_detector(head):
2 slow = fast = head
3 while fast and fast.next:
4 slow = slow.next
5 fast = fast.next.next
6 if slow is fast:
7 return True
8 return False
Variables
slow=3
fast=3

How to think about it

  1. In a cycle, the fast pointer gains one node on the slow each iteration.
  2. After at most n iterations inside the cycle, they coincide.
  3. No cycle ⇔ fast reaches null without meeting slow.

Edge cases to catch in interview

  • Empty list or single node without self-loop → false.
  • Self-loop (node points to itself) → fast == slow at first advance.
  • Head is inside the cycle too → still detected.

Examples

Example 1true
{"values":[3,2,0,-4],"pos":1}

Tail links back to index 1.

Example 2false
{"values":[1,2],"pos":-1}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed