← Two Pointers

Pattern Recognition Drill

#12 — Detect cycle (Floyd's)

Medium Linked Lists

The Problem

Detect if a linked list has a cycle using O(1) space.

What approach would you use?

Think about it before scrolling down.

Key Signals

Two Pointers

Floyd's: slow moves 1 step, fast moves 2. If cycle exists, they meet. O(n) time, O(1) space.

Alt: Hash Map

Store visited nodes in a set — O(n) time but O(n) space. Violates the O(1) space constraint.

Common Trap

The O(1) space constraint is the key signal. Without it, hash set is fine.

← #11 #13 →