Bird
Raised Fist0
DSA Rustprogramming~20 mins

Connected Components Using BFS in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Connected Components Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of BFS Connected Components Count
What is the output of the following Rust code that counts connected components using BFS?
DSA Rust
use std::collections::{VecDeque, HashSet};

fn bfs(start: usize, graph: &Vec<Vec<usize>>, visited: &mut HashSet<usize>) {
    let mut queue = VecDeque::new();
    queue.push_back(start);
    visited.insert(start);

    while let Some(node) = queue.pop_front() {
        for &neighbor in &graph[node] {
            if !visited.contains(&neighbor) {
                visited.insert(neighbor);
                queue.push_back(neighbor);
            }
        }
    }
}

fn connected_components(graph: &Vec<Vec<usize>>) -> usize {
    let mut visited = HashSet::new();
    let mut count = 0;

    for node in 0..graph.len() {
        if !visited.contains(&node) {
            bfs(node, graph, &mut visited);
            count += 1;
        }
    }
    count
}

fn main() {
    let graph = vec![
        vec![1],        // 0 connected to 1
        vec![0, 2],     // 1 connected to 0 and 2
        vec![1],        // 2 connected to 1
        vec![4],        // 3 connected to 4
        vec![3],        // 4 connected to 3
        vec![]          // 5 isolated
    ];
    println!("{}", connected_components(&graph));
}
A2
B3
C4
D1
Attempts:
2 left
💡 Hint
Count how many groups of nodes are connected without crossing to other groups.
🧠 Conceptual
intermediate
1:30remaining
Understanding BFS Role in Connected Components
Why do we use BFS to find connected components in an undirected graph?
ABecause BFS explores all nodes reachable from a start node, marking one connected component at a time.
BBecause BFS removes cycles from the graph to isolate components.
CBecause BFS sorts nodes in ascending order to find components.
DBecause BFS only visits nodes with even indices.
Attempts:
2 left
💡 Hint
Think about how BFS visits nodes layer by layer.
🔧 Debug
advanced
2:30remaining
Identify the Bug in BFS Connected Components Code
What error will this Rust code produce when counting connected components using BFS?
DSA Rust
use std::collections::{VecDeque, HashSet};

fn bfs(start: usize, graph: &Vec<Vec<usize>>, visited: &mut HashSet<usize>) {
    let mut queue = VecDeque::new();
    queue.push_back(start);

    while let Some(node) = queue.pop_front() {
        for &neighbor in &graph[node] {
            if !visited.contains(&neighbor) {
                visited.insert(neighbor);
                queue.push_back(neighbor);
            }
        }
    }
}

fn connected_components(graph: &Vec<Vec<usize>>) -> usize {
    let mut visited = HashSet::new();
    let mut count = 0;

    for node in 0..graph.len() {
        if !visited.contains(&node) {
            bfs(node, graph, &mut visited);
            count += 1;
        }
    }
    count
}

fn main() {
    let graph = vec![
        vec![1],
        vec![0, 2],
        vec![1],
        vec![4],
        vec![3],
        vec![]
    ];
    println!("{}", connected_components(&graph));
}
AThe code causes a runtime panic due to missing visited.insert(start).
BThe code runs correctly and outputs 3.
CThe code causes a compile error because VecDeque is not imported.
DThe code outputs 0 because count is never incremented.
Attempts:
2 left
💡 Hint
Check if the start node is marked visited before BFS loop.
❓ Predict Output
advanced
2:00remaining
Output of BFS Traversal Order
What is the order of nodes visited by BFS starting from node 0 in this graph?
DSA Rust
use std::collections::{VecDeque, HashSet};

fn bfs_order(start: usize, graph: &Vec<Vec<usize>>) -> Vec<usize> {
    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();
    let mut order = Vec::new();

    queue.push_back(start);
    visited.insert(start);

    while let Some(node) = queue.pop_front() {
        order.push(node);
        for &neighbor in &graph[node] {
            if !visited.contains(&neighbor) {
                visited.insert(neighbor);
                queue.push_back(neighbor);
            }
        }
    }
    order
}

fn main() {
    let graph = vec![
        vec![1, 2],    // 0 connected to 1, 2
        vec![0, 3],    // 1 connected to 0, 3
        vec![0, 4],    // 2 connected to 0, 4
        vec![1],       // 3 connected to 1
        vec![2]        // 4 connected to 2
    ];
    let result = bfs_order(0, &graph);
    println!("{:?}", result);
}
A[0, 2, 4, 1, 3]
B[0, 2, 1, 4, 3]
C[0, 1, 3, 2, 4]
D[0, 1, 2, 3, 4]
Attempts:
2 left
💡 Hint
BFS visits neighbors in the order they appear in adjacency lists.
🚀 Application
expert
3:00remaining
Number of Connected Components After Adding Edges
Given an undirected graph with 6 nodes (0 to 5) and edges [[0,1],[1,2],[3,4]], what is the number of connected components after adding edges [[2,3],[4,5]]?
A3
B2
C1
D4
Attempts:
2 left
💡 Hint
Add edges step by step and count how many groups remain connected.

Practice

(1/5)
1. What does the BFS algorithm help find in an undirected graph when used for connected components?
easy
A. All nodes reachable from a starting node forming one connected component
B. The shortest path between two nodes only
C. The maximum degree of any node in the graph
D. The total number of edges in the graph

Solution

  1. Step 1: Understand BFS in context of connected components

    BFS explores all nodes reachable from a starting node, grouping them as one connected component.
  2. Step 2: Differentiate BFS purpose from other graph properties

    While BFS can find shortest paths, here it is used to find connected nodes, not just paths or degrees.
  3. Final Answer:

    All nodes reachable from a starting node forming one connected component -> Option A
  4. Quick Check:

    BFS finds connected components = A [OK]
Hint: BFS visits all nodes in one component starting from any node [OK]
Common Mistakes:
  • Confusing BFS with shortest path only
  • Thinking BFS counts edges or degrees
  • Assuming BFS finds all components at once
2. Which Rust code snippet correctly initializes a queue for BFS traversal?
easy
A. let mut queue: VecDeque<usize> = VecDeque::new();
B. let queue = Vec::new();
C. let mut queue = HashMap::new();
D. let queue: LinkedList<usize> = LinkedList::new();

Solution

  1. Step 1: Identify correct queue type for BFS in Rust

    BFS requires a queue with efficient push/pop from front; VecDeque supports this.
  2. Step 2: Check other options for correctness

    Vec is a stack-like structure, HashMap is a key-value store, LinkedList is less common and less efficient for BFS.
  3. Final Answer:

    let mut queue: VecDeque<usize> = VecDeque::new(); -> Option A
  4. Quick Check:

    Use VecDeque for BFS queue in Rust = C [OK]
Hint: Use VecDeque for queue to push/pop efficiently in BFS [OK]
Common Mistakes:
  • Using Vec which is inefficient for queue operations
  • Using HashMap instead of a queue
  • Confusing LinkedList with VecDeque
3. Given the Rust code below for BFS connected components, what is the output?
use std::collections::{VecDeque, HashMap};

fn bfs(start: usize, graph: &HashMap, visited: &mut Vec<bool>) -> Vec<usize> {
    let mut queue = VecDeque::new();
    let mut component = Vec::new();
    queue.push_back(start);
    visited[start] = true;

    while let Some(node) = queue.pop_front() {
        component.push(node);
        if let Some(neighbors) = graph.get(&node) {
            for &neighbor in neighbors {
                if !visited[neighbor] {
                    visited[neighbor] = true;
                    queue.push_back(neighbor);
                }
            }
        }
    }
    component
}

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

    let mut visited = vec![false; 5];
    let comp1 = bfs(0, &graph, &mut visited);
    let comp2 = bfs(3, &graph, &mut visited);

    println!("Component 1: {:?}", comp1);
    println!("Component 2: {:?}", comp2);
}
medium
A. Component 1: [1, 0, 2] Component 2: [4, 3]
B. Component 1: [0, 1] Component 2: [3, 4, 2]
C. Component 1: [0, 2] Component 2: [1, 3, 4]
D. Component 1: [0, 1, 2] Component 2: [3, 4]

Solution

  1. Step 1: Trace BFS from node 0

    Starting at 0, BFS visits 0, then 1, then 2. So component 1 is [0, 1, 2].
  2. Step 2: Trace BFS from node 3

    Starting at 3, BFS visits 3, then 4. So component 2 is [3, 4].
  3. Final Answer:

    Component 1: [0, 1, 2] Component 2: [3, 4] -> Option D
  4. Quick Check:

    BFS groups connected nodes correctly = D [OK]
Hint: Follow BFS queue order to list connected nodes [OK]
Common Mistakes:
  • Mixing nodes between components
  • Ignoring visited array updates
  • Assuming BFS order is sorted
4. Identify the bug in this BFS connected components Rust code snippet:
fn bfs(start: usize, graph: &HashMap, visited: &mut Vec<bool>) -> Vec<usize> {
    let mut queue = VecDeque::new();
    let mut component = Vec::new();
    queue.push_back(start);
    // visited[start] = true;  // Missing this line

    while let Some(node) = queue.pop_front() {
        component.push(node);
        if let Some(neighbors) = graph.get(&node) {
            for &neighbor in neighbors {
                if !visited[neighbor] {
                    visited[neighbor] = true;
                    queue.push_back(neighbor);
                }
            }
        }
    }
    component
}
medium
A. Neighbors are not checked for existence
B. The queue is not initialized properly
C. The starting node is not marked visited before BFS loop
D. Component vector is not returned

Solution

  1. Step 1: Check visited marking for start node

    The line marking start node as visited is commented out, so BFS may revisit it causing infinite loop or wrong results.
  2. Step 2: Verify other parts of code

    Queue is initialized, neighbors checked, and component returned correctly.
  3. Final Answer:

    The starting node is not marked visited before BFS loop -> Option C
  4. Quick Check:

    Mark start visited before BFS = A [OK]
Hint: Always mark start node visited before BFS loop [OK]
Common Mistakes:
  • Forgetting to mark start visited
  • Not initializing queue
  • Ignoring neighbor existence check
5. You have a graph with 6 nodes (0 to 5) and edges: (0-1), (1-2), (3-4). Using BFS connected components, how many components are there and which nodes belong to each? Choose the correct grouping.
medium
A. 2 components: [0,1,2,3,4], [5]
B. 3 components: [0,1,2], [3,4], [5] (isolated node)
C. 1 component: [0,1,2,3,4,5]
D. 4 components: [0], [1,2], [3,4], [5]

Solution

  1. Step 1: Identify connected groups from edges

    Edges connect 0-1-2 forming one component, 3-4 forming second, and node 5 is isolated alone.
  2. Step 2: Count components and list nodes

    There are 3 components: [0,1,2], [3,4], and [5].
  3. Final Answer:

    3 components: [0,1,2], [3,4], [5] (isolated node) -> Option B
  4. Quick Check:

    Count isolated and connected groups correctly = B [OK]
Hint: Count isolated nodes as separate components [OK]
Common Mistakes:
  • Grouping isolated node with others
  • Merging disconnected components
  • Miscounting total components
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