Topological Sort 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 this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Topological Sort runs in O(V+E) time and O(V) space, in Rust as in every other language.
- ✓std::collections::VecDeque is the real queue (O(1) push_back/pop_front, unlike Vec::remove(0) which is O(n)); std::collections::BinaryHeap plus std::cmp::Reverse gives a min-heap variant for a canonical, lexicographically-smallest ordering.
- ✓VecDeque for the plain FIFO version, always, reaching for Vec and Vec::remove(0) is the Rust-specific shape of the same trap every other language here has, and it compiles without a single warning, so it is purely a code-review catch.
- ✓The Rust trap: std::collections::BinaryHeap is a MAX-heap by default, so an implementation that wants Kahn's algorithm to process ready nodes in ascending order (for a deterministic, lexicographically-smallest topological order) has to wrap every pushed value in std::cmp::Reverse, forgetting the wrapper is a silent logic bug, not a compile error, since BinaryHeap<T> and BinaryHeap<Reverse<T>> are both perfectly valid types that simply produce opposite orderings.
- ✓O(V+E) with VecDeque, whose push_back and pop_front are both genuinely O(1) amortized because it is backed by a ring buffer, not a re-indexed contiguous array like Vec.
What Topological Sort actually is
Topological Sort in Rust: what you actually reach for
Rust implementation
use std::collections::{HashMap, VecDeque};
fn topo_order(graph: &HashMap<String, Vec<String>>) -> Result<Vec<String>, &'static str> {
let mut indegree: HashMap<String, usize> =
graph.keys().map(|k| (k.clone(), 0)).collect();
for nexts in graph.values() {
for n in nexts {
*indegree.entry(n.clone()).or_insert(0) += 1;
}
}
let mut queue: VecDeque<String> = // VecDeque: O(1) at both ends, unlike Vec::remove(0)
indegree.iter().filter(|&(_, &d)| d == 0).map(|(n, _)| n.clone()).collect();
let mut order = Vec::with_capacity(indegree.len());
while let Some(node) = queue.pop_front() {
if let Some(nexts) = graph.get(&node) {
for next in nexts {
let d = indegree.get_mut(next).unwrap();
*d -= 1;
if *d == 0 {
queue.push_back(next.clone());
}
}
}
order.push(node);
}
if order.len() != indegree.len() {
return Err("not a DAG: cycle present");
}
Ok(order)
}
// petgraph does this (and cycle detection) without hand-rolling Kahn's:
// petgraph::algo::toposort(&graph, None) -> Result<Vec<NodeIndex>, Cycle<NodeIndex>>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 Topological Sort?
std::collections::VecDeque is the real queue (O(1) push_back/pop_front, unlike Vec::remove(0) which is O(n)); std::collections::BinaryHeap plus std::cmp::Reverse gives a min-heap variant for a canonical, lexicographically-smallest ordering. petgraph::algo::toposort(&graph, None) does the whole thing, including cycle detection, and hands back Result<Vec<NodeIndex>, Cycle<NodeIndex>> so a cyclic input is a value you are forced to handle, not an exception you can forget to catch.
What is the most common Rust mistake when implementing Topological Sort?
std::collections::BinaryHeap is a MAX-heap by default, so an implementation that wants Kahn's algorithm to process ready nodes in ascending order (for a deterministic, lexicographically-smallest topological order) has to wrap every pushed value in std::cmp::Reverse, forgetting the wrapper is a silent logic bug, not a compile error, since BinaryHeap<T> and BinaryHeap<Reverse<T>> are both perfectly valid types that simply produce opposite orderings.
How does Topological Sort actually perform in Rust?
O(V+E) with VecDeque, whose push_back and pop_front are both genuinely O(1) amortized because it is backed by a ring buffer, not a re-indexed contiguous array like Vec. BinaryHeap operations are O(log n) per push/pop, so the deterministic-ordering variant is O((V+E) log V), a real, correct complexity difference from the plain-FIFO version of the same algorithm, not just a constant-factor one. Time complexity is O(V+E) and space is O(V).
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.