Chapter 04 - Fast and Slow Pointers
Two pointers moving at different speeds. If they meet, there is a cycle. When the fast one reaches the end, the slow one is halfway.
This page is the entry point of chapter 4 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
The slow pointer moves one step at a time, the fast one two steps. On a list with a cycle, the fast pointer eventually catches up with the slow one: this is Floyd’s cycle detection, in \(O(n)\) time and \(O(1)\) space, without storing visited nodes. On a list without a cycle, when the fast pointer reaches the end, the slow pointer stands in the middle.
When to reach for it
- Detect a cycle in a linked list, or in any sequence where each value determines the next one.
- Find the middle of a list in a single pass.
- The “list” may be implicit: for happy numbers, the next node is the sum of the squares of the digits.
In Rust
- With
Option<Box<Node>>, two cursors are only possible with shared references: walk withas_ref()andas_deref(). - A real cycle needs shared ownership, hence
Rc<RefCell<Node>>, andRc::ptr_eqto compare nodes by identity, not by value. - On implicit sequences, there is no list at all: two variables and a
next(n)function are enough.
Problems in this chapter
- p073 - Linked List Loop: Linked List Loop (Fast and Slow Pointers) solved in Rust: determine whether a singly linked list contains a cycle.
- p077 - Linked List Midpoint: Linked List Midpoint (Fast and Slow Pointers) solved in Rust: return the middle node of a singly linked list, or the second one if there are two.
- p080 - Happy Number: Happy Number (Fast Slow Pointers), solved in Rust. Given an integer determine if it is a happy number. Examples: 23 is happy, 116 is unhappy.
Other chapters
All the chapters, with every problem, are listed on the series page.