Bird
Raised Fist0
DSA Rustprogramming~20 mins

Cycle Detection in Undirected Graph in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cycle Detection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of cycle detection on a simple graph
What is the output of the following Rust code that detects a cycle in an undirected graph?
DSA Rust
use std::collections::HashMap;
use std::collections::HashSet;

fn dfs(
    node: usize,
    parent: Option<usize>,
    graph: &HashMap<usize, Vec<usize>>,
    visited: &mut HashSet<usize>,
) -> bool {
    visited.insert(node);
    for &neighbor in graph.get(&node).unwrap_or(&Vec::new()) {
        if !visited.contains(&neighbor) {
            if dfs(neighbor, Some(node), graph, visited) {
                return true;
            }
        } else if Some(neighbor) != parent {
            return true;
        }
    }
    false
}

fn has_cycle(graph: &HashMap<usize, Vec<usize>>) -> bool {
    let mut visited = HashSet::new();
    for &node in graph.keys() {
        if !visited.contains(&node) {
            if dfs(node, None, graph, &mut visited) {
                return true;
            }
        }
    }
    false
}

fn main() {
    let mut graph = HashMap::new();
    graph.insert(1, vec![2]);
    graph.insert(2, vec![1, 3]);
    graph.insert(3, vec![2, 4]);
    graph.insert(4, vec![3, 1]);

    println!("{}", has_cycle(&graph));
}
ACompilation error
Bfalse
Ctrue
DRuntime panic
Attempts:
2 left
💡 Hint
Think about whether the graph contains a loop connecting nodes back to an earlier node.
❓ Predict Output
intermediate
2:00remaining
Cycle detection output on a tree structure
What does the following Rust code print when checking for a cycle in a tree (acyclic graph)?
DSA Rust
use std::collections::{HashMap, HashSet};

fn dfs(
    node: usize,
    parent: Option<usize>,
    graph: &HashMap<usize, Vec<usize>>,
    visited: &mut HashSet<usize>,
) -> bool {
    visited.insert(node);
    for &neighbor in graph.get(&node).unwrap_or(&Vec::new()) {
        if !visited.contains(&neighbor) {
            if dfs(neighbor, Some(node), graph, visited) {
                return true;
            }
        } else if Some(neighbor) != parent {
            return true;
        }
    }
    false
}

fn has_cycle(graph: &HashMap<usize, Vec<usize>>) -> bool {
    let mut visited = HashSet::new();
    for &node in graph.keys() {
        if !visited.contains(&node) {
            if dfs(node, None, graph, &mut visited) {
                return true;
            }
        }
    }
    false
}

fn main() {
    let mut graph = HashMap::new();
    graph.insert(1, vec![2, 3]);
    graph.insert(2, vec![1]);
    graph.insert(3, vec![1, 4]);
    graph.insert(4, vec![3]);

    println!("{}", has_cycle(&graph));
}
Atrue
BRuntime panic
CCompilation error
Dfalse
Attempts:
2 left
💡 Hint
A tree has no cycles by definition.
🔧 Debug
advanced
2:30remaining
Identify the error causing incorrect cycle detection
The following Rust code is intended to detect cycles in an undirected graph but always returns false even when a cycle exists. What is the bug?
DSA Rust
use std::collections::{HashMap, HashSet};

fn dfs(
    node: usize,
    parent: usize,
    graph: &HashMap<usize, Vec<usize>>,
    visited: &mut HashSet<usize>,
) -> bool {
    visited.insert(node);
    for &neighbor in graph.get(&node).unwrap_or(&Vec::new()) {
        if !visited.contains(&neighbor) {
            if dfs(neighbor, node, graph, visited) {
                return true;
            }
        } else if neighbor != parent {
            return true;
        }
    }
    false
}

fn has_cycle(graph: &HashMap<usize, Vec<usize>>) -> bool {
    let mut visited = HashSet::new();
    for &node in graph.keys() {
        if !visited.contains(&node) {
            if dfs(node, 0, graph, &mut visited) {
                return true;
            }
        }
    }
    false
}

fn main() {
    let mut graph = HashMap::new();
    graph.insert(1, vec![2]);
    graph.insert(2, vec![1, 3]);
    graph.insert(3, vec![2, 1]);

    println!("{}", has_cycle(&graph));
}
AThe parent parameter should be Option<usize> to allow None for the root node.
BThe visited set is not cleared between DFS calls.
CThe graph edges are not bidirectional.
DThe DFS does not mark nodes as visited.
Attempts:
2 left
💡 Hint
Check how the parent node is passed for the first DFS call.
❓ Predict Output
advanced
2:00remaining
Output of cycle detection on disconnected graph with one cycle
What is the output of the following Rust code detecting cycles in a disconnected undirected graph where only one component has a cycle?
DSA Rust
use std::collections::{HashMap, HashSet};

fn dfs(
    node: usize,
    parent: Option<usize>,
    graph: &HashMap<usize, Vec<usize>>,
    visited: &mut HashSet<usize>,
) -> bool {
    visited.insert(node);
    for &neighbor in graph.get(&node).unwrap_or(&Vec::new()) {
        if !visited.contains(&neighbor) {
            if dfs(neighbor, Some(node), graph, visited) {
                return true;
            }
        } else if Some(neighbor) != parent {
            return true;
        }
    }
    false
}

fn has_cycle(graph: &HashMap<usize, Vec<usize>>) -> bool {
    let mut visited = HashSet::new();
    for &node in graph.keys() {
        if !visited.contains(&node) {
            if dfs(node, None, graph, &mut visited) {
                return true;
            }
        }
    }
    false
}

fn main() {
    let mut graph = HashMap::new();
    // Component 1 (no cycle)
    graph.insert(1, vec![2]);
    graph.insert(2, vec![1]);
    // Component 2 (cycle: 3-4-5-3)
    graph.insert(3, vec![4, 5]);
    graph.insert(4, vec![3, 5]);
    graph.insert(5, vec![3, 4]);

    println!("{}", has_cycle(&graph));
}
Afalse
Btrue
CCompilation error
DRuntime panic
Attempts:
2 left
💡 Hint
Check if the algorithm detects cycles in any connected component.
🧠 Conceptual
expert
1:30remaining
Why does DFS use a parent parameter in cycle detection for undirected graphs?
In cycle detection for undirected graphs using DFS, why is it necessary to pass the parent node to the DFS function?
ATo avoid falsely detecting the edge back to the parent as a cycle.
BTo keep track of the depth of the DFS traversal.
CTo mark nodes as visited in the correct order.
DTo store the path of nodes visited so far.
Attempts:
2 left
💡 Hint
Think about why revisiting the immediate previous node should not count as a cycle.

Practice

(1/5)
1. What is the main idea behind detecting a cycle in an undirected graph using DFS?
easy
A. If we visit a node that is already visited and is not the parent, a cycle exists.
B. If all nodes are visited exactly once, the graph has a cycle.
C. If the graph has more edges than nodes, it must have a cycle.
D. If the graph is disconnected, it contains a cycle.

Solution

  1. Step 1: Understand DFS traversal in undirected graph

    DFS visits nodes and tracks the parent node to avoid false cycle detection.
  2. Step 2: Detect cycle condition

    If a visited node is found that is not the parent, it means a back edge exists, indicating a cycle.
  3. Final Answer:

    If we visit a node that is already visited and is not the parent, a cycle exists. -> Option A
  4. Quick Check:

    Cycle detection in undirected graph = check visited & parent [OK]
Hint: Check visited nodes excluding parent during DFS to find cycles [OK]
Common Mistakes:
  • Ignoring the parent node when checking visited nodes
  • Assuming disconnected graph always has cycles
  • Confusing cycle detection logic with directed graphs
  • Counting edges vs nodes incorrectly
2. Which Rust code snippet correctly initializes an adjacency list for an undirected graph with 3 nodes?
easy
A. let graph = vec![vec![]; 3]; graph[0].push(1); graph[1].push(0); graph[1].push(2); graph[2].push(1);
B. let mut graph = vec![vec![]; 3]; graph[0].push(1); graph[1].push(0); graph[1].push(2); graph[2].push(1);
C. let mut graph = vec![vec![]; 3]; graph[0].push(1); graph[1].push(2); graph[2].push(1);
D. let mut graph = vec![vec![]; 3]; graph[0].push(1); graph[1].push(0); graph[2].push(1);

Solution

  1. Step 1: Initialize mutable adjacency list

    Use let mut graph = vec![vec![]; 3]; to create a mutable vector of vectors for 3 nodes.
  2. Step 2: Add edges for undirected graph

    For each edge, add both directions: node 0 to 1 and node 1 to 0, node 1 to 2 and node 2 to 1.
  3. Final Answer:

    let mut graph = vec![vec![]; 3]; graph[0].push(1); graph[1].push(0); graph[1].push(2); graph[2].push(1); -> Option B
  4. Quick Check:

    Mutable adjacency list with bidirectional edges = correct initialization [OK]
Hint: Use 'mut' and push edges both ways for undirected graph [OK]
Common Mistakes:
  • Forgetting 'mut' keyword for mutable vector
  • Adding edges only one way in undirected graph
  • Trying to push to immutable vector
  • Incorrect vector initialization syntax
3. What will be the output of the following Rust code snippet detecting cycle in an undirected graph?
fn dfs(node: usize, parent: usize, graph: &Vec, visited: &mut Vec<bool>) -> bool {
    visited[node] = true;
    for &neighbor in &graph[node] {
        if !visited[neighbor] {
            if dfs(neighbor, node, graph, visited) {
                return true;
            }
        } else if neighbor != parent {
            return true;
        }
    }
    false
}

fn main() {
    let mut graph = vec![vec![]; 4];
    graph[0].push(1); graph[1].push(0);
    graph[1].push(2); graph[2].push(1);
    graph[2].push(3); graph[3].push(2);
    graph[3].push(1); graph[1].push(3);

    let mut visited = vec![false; 4];
    let has_cycle = dfs(0, usize::MAX, &graph, &mut visited);
    println!("{}", has_cycle);
}
medium
A. Runtime panic
B. false
C. true
D. Compilation error

Solution

  1. Step 1: Analyze graph edges and structure

    The graph edges form a cycle: 1-2-3-1, so cycle exists.
  2. Step 2: Trace DFS cycle detection logic

    DFS visits nodes and finds a visited neighbor (1) not equal to parent, returning true.
  3. Final Answer:

    true -> Option C
  4. Quick Check:

    Cycle detected in DFS = true [OK]
Hint: Look for back edges to visited nodes excluding parent [OK]
Common Mistakes:
  • Ignoring the edge from 3 to 1 forming a cycle
  • Confusing parent node with visited node
  • Assuming no cycle if start node is 0
  • Misreading DFS return conditions
4. Identify the bug in this Rust DFS cycle detection code for an undirected graph:
fn dfs(node: usize, parent: usize, graph: &Vec, visited: &mut Vec<bool>) -> bool {
    visited[node] = true;
    for &neighbor in &graph[node] {
        if visited[neighbor] {
            if neighbor != parent {
                return true;
            }
        } else {
            dfs(neighbor, node, graph, visited);
        }
    }
    false
}
medium
A. Missing return statement for recursive dfs call
B. Incorrect parent check condition
C. Visited vector should be immutable
D. Graph should be mutable

Solution

  1. Step 1: Check recursive call usage

    The recursive call to dfs is made but its result is ignored, missing return propagation.
  2. Step 2: Fix by returning recursive call result

    Return the result of dfs(neighbor, node, graph, visited) to propagate cycle detection upwards.
  3. Final Answer:

    Missing return statement for recursive dfs call -> Option A
  4. Quick Check:

    Return recursive dfs result to detect cycles correctly [OK]
Hint: Always return recursive call result in DFS for cycle detection [OK]
Common Mistakes:
  • Ignoring return value of recursive DFS calls
  • Confusing parent check logic
  • Using immutable visited vector incorrectly
  • Assuming graph mutability is required here
5. Given an undirected graph represented as adjacency list in Rust, how can you modify the DFS cycle detection to handle disconnected graphs and detect cycles in all components? Choose the best approach.
hard
A. Use BFS instead of DFS for cycle detection.
B. Run DFS only from node 0, assuming graph is connected.
C. Mark all nodes visited initially and then run DFS once.
D. Run DFS from every unvisited node in a loop to cover all components.

Solution

  1. Step 1: Understand disconnected graph scenario

    Disconnected graphs have multiple components; DFS from one node covers only one component.
  2. Step 2: Modify DFS to run on all components

    Loop over all nodes, run DFS if node is unvisited to detect cycles in every component.
  3. Final Answer:

    Run DFS from every unvisited node in a loop to cover all components. -> Option D
  4. Quick Check:

    Cycle detection in disconnected graph = DFS from all unvisited nodes [OK]
Hint: Loop DFS over all nodes to cover disconnected components [OK]
Common Mistakes:
  • Assuming graph is always connected
  • Running DFS only once from node 0
  • Using BFS without cycle detection logic
  • Marking all nodes visited before DFS
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard