Challenge - 5 Problems
Cycle Detection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of cycle detection on a simple directed graph
What is the output of the following Rust code that detects a cycle in a directed graph?
DSA Rust
use std::collections::HashMap;
use std::collections::HashSet;
fn has_cycle(
node: usize,
graph: &HashMap<usize, Vec<usize>>,
visited: &mut HashSet<usize>,
stack: &mut HashSet<usize>,
) -> bool {
if stack.contains(&node) {
return true;
}
if visited.contains(&node) {
return false;
}
visited.insert(node);
stack.insert(node);
if let Some(neighbors) = graph.get(&node) {
for &neighbor in neighbors {
if has_cycle(neighbor, graph, visited, stack) {
return true;
}
}
}
stack.remove(&node);
false
}
fn main() {
let mut graph = HashMap::new();
graph.insert(1, vec![2]);
graph.insert(2, vec![3]);
graph.insert(3, vec![4]);
graph.insert(4, vec![2]);
let mut visited = HashSet::new();
let mut stack = HashSet::new();
let result = has_cycle(1, &graph, &mut visited, &mut stack);
println!("{}", result);
}Attempts:
2 left
💡 Hint
Trace the recursion and check if the function detects a back edge in the graph.
✗ Incorrect
The graph has a cycle: 2 -> 3 -> 4 -> 2. The function detects this cycle and returns true.
❓ Predict Output
intermediateOutput of cycle detection on an acyclic directed graph
What is the output of the following Rust code that detects a cycle in a directed graph without cycles?
DSA Rust
use std::collections::HashMap;
use std::collections::HashSet;
fn has_cycle(
node: usize,
graph: &HashMap<usize, Vec<usize>>,
visited: &mut HashSet<usize>,
stack: &mut HashSet<usize>,
) -> bool {
if stack.contains(&node) {
return true;
}
if visited.contains(&node) {
return false;
}
visited.insert(node);
stack.insert(node);
if let Some(neighbors) = graph.get(&node) {
for &neighbor in neighbors {
if has_cycle(neighbor, graph, visited, stack) {
return true;
}
}
}
stack.remove(&node);
false
}
fn main() {
let mut graph = HashMap::new();
graph.insert(1, vec![2]);
graph.insert(2, vec![3]);
graph.insert(3, vec![4]);
graph.insert(4, vec![]);
let mut visited = HashSet::new();
let mut stack = HashSet::new();
let result = has_cycle(1, &graph, &mut visited, &mut stack);
println!("{}", result);
}Attempts:
2 left
💡 Hint
Check if any node is revisited while still in the recursion stack.
✗ Incorrect
The graph has no cycles, so the function returns false.
🔧 Debug
advancedIdentify the error in cycle detection code
What error does the following Rust code produce when detecting a cycle in a directed graph?
DSA Rust
use std::collections::HashMap;
use std::collections::HashSet;
fn has_cycle(
node: usize,
graph: &HashMap<usize, Vec<usize>>,
visited: &mut HashSet<usize>,
stack: &mut HashSet<usize>,
) -> bool {
if stack.contains(&node) {
return true;
}
if visited.contains(&node) {
return false;
}
visited.insert(node);
stack.insert(node);
if let Some(neighbors) = graph.get(&node) {
for neighbor in neighbors {
if has_cycle(*neighbor, graph, visited, stack) {
return true;
}
}
}
stack.remove(&node);
false
}
fn main() {
let mut graph = HashMap::new();
graph.insert(1, vec![2]);
graph.insert(2, vec![3]);
graph.insert(3, vec![1]);
let mut visited = HashSet::new();
let mut stack = HashSet::new();
let result = has_cycle(1, &graph, &mut visited, &mut stack);
println!("{}", result);
}Attempts:
2 left
💡 Hint
Check how neighbors are accessed and dereferenced in the loop.
✗ Incorrect
The code correctly detects the cycle 1 -> 2 -> 3 -> 1 and prints true.
🧠 Conceptual
advancedWhy use a recursion stack in cycle detection?
In cycle detection for directed graphs, why do we use a recursion stack (or call stack tracking) alongside a visited set?
Attempts:
2 left
💡 Hint
Think about what a back edge means in a directed graph DFS.
✗ Incorrect
The recursion stack helps detect back edges, which indicate cycles in directed graphs.
🚀 Application
expertNumber of nodes in cycle detected by algorithm
Given the following directed graph and cycle detection code, how many nodes are part of the detected cycle?
DSA Rust
use std::collections::{HashMap, HashSet};
fn find_cycle_nodes(
node: usize,
graph: &HashMap<usize, Vec<usize>>,
visited: &mut HashSet<usize>,
stack: &mut Vec<usize>,
cycle_nodes: &mut HashSet<usize>,
) -> bool {
if stack.contains(&node) {
let pos = stack.iter().position(|&x| x == node).unwrap();
for &n in &stack[pos..] {
cycle_nodes.insert(n);
}
return true;
}
if visited.contains(&node) {
return false;
}
visited.insert(node);
stack.push(node);
if let Some(neighbors) = graph.get(&node) {
for &neighbor in neighbors {
if find_cycle_nodes(neighbor, graph, visited, stack, cycle_nodes) {
return true;
}
}
}
stack.pop();
false
}
fn main() {
let mut graph = HashMap::new();
graph.insert(1, vec![2]);
graph.insert(2, vec![3, 4]);
graph.insert(3, vec![1]);
graph.insert(4, vec![5]);
graph.insert(5, vec![]);
let mut visited = HashSet::new();
let mut stack = Vec::new();
let mut cycle_nodes = HashSet::new();
find_cycle_nodes(1, &graph, &mut visited, &mut stack, &mut cycle_nodes);
println!("{}", cycle_nodes.len());
}Attempts:
2 left
💡 Hint
Identify the cycle nodes from the graph edges and the recursion stack slice.
✗ Incorrect
The cycle is 1 -> 2 -> 3 -> 1, so 3 nodes are in the cycle.
