Repaso
EspaƱol
Algorithms & DSIntermediateALG-07

Detect a cycle in a linked list with O(1) extra space?

Options

  1. Store each visited node in a hash set and look for repeats
  2. Floyd's: a slow and a fast pointer meet when there is a cycle (Correct option)
  3. Reverse the list in place and compare it with the original
  4. Sort the nodes by value and look for any repeated nodes

Answer

Floyd's tortoise and hare: slow moves 1, fast moves 2; they meet if there is a cycle

Why

Use two pointers: the slow one moves 1 node per step, the fast one 2 nodes.

If the list ends, there is no cycle. If there IS a cycle, the fast pointer eventually laps the slow one inside the loop and they meet, like two runners on a circular track.

A set of visited nodes also works but uses O(n) memory.

Remember

Cycle detection: fast and slow pointers.

Key terms

Practice this question in Repaso