Cycle Detection Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn your Graph Algorithms question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Cycle Detection runs in O(V+E) time and O(V) space, in Rust as in every other language.
- ✓std::collections::HashMap for the adjacency list and the per-node state, and, critically, no Rc<RefCell<Node>> anywhere in the idiomatic version: representing a graph with actual owned pointers between nodes fights the borrow checker precisely because graphs routinely have cycles, so the standard approach indexes nodes by a plain usize or HashMap key instead of a real reference.
- ✓Represent the graph as indices into a Vec or keys into a HashMap, never as Rc<RefCell<Node>> with back-pointers, unless you have a specific reason (like needing to hand a live node out to a caller) that an index-based graph cannot satisfy, a reviewer will ask why you reached for shared, interior-mutable ownership before reaching for an index.
- ✓The Rust trap: If you do build the graph with Rc<RefCell<Node>> and a node holds an Rc that transitively points back to itself, that reference cycle's count never reaches zero and the whole cluster leaks for the life of the program, a distinct problem from the logical graph cycle you are trying to detect, documented explicitly in the Rust book precisely because the borrow checker cannot catch it: Rc/RefCell opts out of the compile-time cycle-safety Rust otherwise gives you.
- ✓O(V+E) same as everywhere else, and the index/HashMap-based version pays only a hash lookup per edge traversal with zero allocation inside the loop, since state is a plain enum stored by value.
What Cycle Detection actually is
Cycle Detection in Rust: what you actually reach for
Rust implementation
use std::collections::HashMap;
#[derive(Clone, Copy, PartialEq)]
enum State { White, Gray, Black }
// Index-based graph: no Rc<RefCell<_>>, so there is no reference-cycle-leak
// question separate from the logical cycle we are looking for.
fn has_cycle(graph: &HashMap<usize, Vec<usize>>) -> bool {
let mut state: HashMap<usize, State> =
graph.keys().map(|&k| (k, State::White)).collect();
let starts: Vec<usize> = graph.keys().copied().collect();
for start in starts {
if state.get(&start).copied() != Some(State::White) {
continue;
}
let mut stack: Vec<(usize, usize)> = vec![(start, 0)];
state.insert(start, State::Gray);
while let Some(&(node, i)) = stack.last() {
let children = graph.get(&node).map(Vec::as_slice).unwrap_or(&[]);
if i < children.len() {
stack.last_mut().unwrap().1 += 1;
let child = children[i];
match state.get(&child).copied() {
Some(State::Gray) => return true, // back edge
Some(State::White) | None => {
state.insert(child, State::Gray);
stack.push((child, 0));
}
_ => {}
}
} else {
state.insert(node, State::Black);
stack.pop();
}
}
}
false
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Cycle Detection?
std::collections::HashMap for the adjacency list and the per-node state, and, critically, no Rc<RefCell<Node>> anywhere in the idiomatic version: representing a graph with actual owned pointers between nodes fights the borrow checker precisely because graphs routinely have cycles, so the standard approach indexes nodes by a plain usize or HashMap key instead of a real reference. For real workloads the petgraph crate ships is_cyclic_directed and toposort so you rarely hand-roll this at all.
What is the most common Rust mistake when implementing Cycle Detection?
If you do build the graph with Rc<RefCell<Node>> and a node holds an Rc that transitively points back to itself, that reference cycle's count never reaches zero and the whole cluster leaks for the life of the program, a distinct problem from the logical graph cycle you are trying to detect, documented explicitly in the Rust book precisely because the borrow checker cannot catch it: Rc/RefCell opts out of the compile-time cycle-safety Rust otherwise gives you. The fix, when you need back-pointers at all, is Weak for the back-edge so it does not hold a strong count.
How does Cycle Detection actually perform in Rust?
O(V+E) same as everywhere else, and the index/HashMap-based version pays only a hash lookup per edge traversal with zero allocation inside the loop, since state is a plain enum stored by value. The Rc<RefCell<Node>> version pays a heap allocation per node at construction, a runtime borrow check (RefCell::borrow/borrow_mut) on every access that can panic if you ever accidentally hold two conflicting borrows, and reference-count increments/decrements on every Rc clone, none of that changes the O(V+E) bound, but it is real per-operation cost the index-based version never pays. Time complexity is O(V+E) and space is O(V).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.