Detect Loop in Linked List Visualization & Animation
Detects a cycle in a linked list using Floyd's fast-slow pointer algorithm; O(n) time, O(1) space.
## What is it?
Detect whether a singly linked list contains a cycle (loop). Uses Floyd's Cycle Detection algorithm (fast and slow pointers) in O(1) space.
## How it works
- Start `slow` and `fast` both at `head`
- Move `slow` one step, `fast` two steps per iteration
- If `fast` or `fast.next` becomes `null` → no cycle (list is finite)
- If `slow == fast` at any point → a cycle exists (they met inside the cycle)
**Why it works:** In a cycle, the fast pointer gains one step on the slow pointer each iteration; they must eventually meet.
## When to use
- Detecting infinite loops in linked lists
- As the first step of "Find Cycle Start" problems
- Validating integrity of pointer structures
## Key Points
- O(n) time — they meet in at most `n` steps
- O(1) space — no visited set needed
- Extension: to find where the cycle starts, see the "Find Cycle Start" algorithm
Category: algorithms
Difficulty: beginner
- fast-and-slow-pointers
- linked-list
Time Complexity: O(n)
Space Complexity: O(1)
View Detect Loop in Linked List Visualization