Skip to content
StackDecode
Linked listsAnimated

Detect and Remove Loop

Find the cycle start with Floyd, then cut the last node.

Time

O(n)

Extra space

O(1)

Use it for

Repairing corrupted lists.

How it works

  1. Detect the cycle with slow and fast pointers, as in Floyd’s algorithm.
  2. When they meet, move one pointer back to the head and advance both one step at a time. They meet exactly at the node where the cycle begins.
  3. Walk around until you reach the node whose next is that start node: it is the last node in the loop.
  4. Set its next to empty to break the loop.

Watch it run

Loading animation…