Bird
Raised Fist0
DSA Goprogramming~20 mins

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

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
BFS 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 this Go code that counts connected components using BFS?
DSA Go
package main

import "fmt"

func bfs(graph map[int][]int, start int, visited map[int]bool) {
    queue := []int{start}
    visited[start] = true
    for len(queue) > 0 {
        node := queue[0]
        queue = queue[1:]
        for _, neighbor := range graph[node] {
            if !visited[neighbor] {
                visited[neighbor] = true
                queue = append(queue, neighbor)
            }
        }
    }
}

func countConnectedComponents(graph map[int][]int) int {
    visited := make(map[int]bool)
    count := 0
    for node := range graph {
        if !visited[node] {
            bfs(graph, node, visited)
            count++
        }
    }
    return count
}

func main() {
    graph := map[int][]int{
        1: {2},
        2: {1, 3},
        3: {2},
        4: {5},
        5: {4},
        6: {},
    }
    fmt.Println(countConnectedComponents(graph))
}
A3
B2
C4
D1
Attempts:
2 left
💡 Hint
Count how many groups of nodes are connected without crossing to others.
🔧 Debug
intermediate
2:00remaining
Identify the error in BFS traversal code
What error will this Go code produce when running BFS on the graph?
DSA Go
package main

import "fmt"

func bfs(graph map[int][]int, start int, visited map[int]bool) {
    queue := []int{start}
    visited[start] = true
    for len(queue) > 0 {
        node := queue[0]
        queue = queue[1:]
        for _, neighbor := range graph[node] {
            if visited[neighbor] {
                visited[neighbor] = true
                queue = append(queue, neighbor)
            }
        }
    }
}

func main() {
    graph := map[int][]int{
        1: {1,2},
        2: {1, 3},
        3: {2},
    }
    visited := make(map[int]bool)
    bfs(graph, 1, visited)
    fmt.Println(visited)
}
ASyntax error: missing colon
BNo output, infinite loop
CRuntime panic: index out of range
Dmap[1:true 2:true 3:true]
Attempts:
2 left
💡 Hint
Check the condition that adds neighbors to the queue.
🧠 Conceptual
advanced
1:30remaining
Why use BFS for Connected Components?
Why is BFS a good choice to find connected components in an undirected graph?
ABFS explores all nodes reachable from a start node layer by layer, ensuring all nodes in a component are visited before moving on.
BBFS uses less memory than DFS in all cases.
CBFS only works on directed graphs, so it is not suitable here.
DBFS sorts the nodes which helps identify components.
Attempts:
2 left
💡 Hint
Think about how BFS visits nodes connected to the start node.
❓ Predict Output
advanced
2:00remaining
Output after BFS visits nodes in a graph
What is the printed output of the visited map after running BFS starting from node 2?
DSA Go
package main

import "fmt"

func bfs(graph map[int][]int, start int, visited map[int]bool) {
    queue := []int{start}
    visited[start] = true
    for len(queue) > 0 {
        node := queue[0]
        queue = queue[1:]
        for _, neighbor := range graph[node] {
            if !visited[neighbor] {
                visited[neighbor] = true
                queue = append(queue, neighbor)
            }
        }
    }
}

func main() {
    graph := map[int][]int{
        1: {2, 3},
        2: {1, 4},
        3: {1},
        4: {2},
        5: {},
    }
    visited := make(map[int]bool)
    for node := range graph {
        visited[node] = false
    }
    bfs(graph, 2, visited)
    fmt.Println(visited)
}
Amap[1:true 2:true 3:false 4:true 5:false]
Bmap[2:true 4:true]
Cmap[1:true 2:true 3:true 4:true 5:true]
Dmap[1:true 2:true 3:true 4:true 5:false]
Attempts:
2 left
💡 Hint
Check which nodes are reachable from node 2.
🚀 Application
expert
2:30remaining
Number of Connected Components in a Large Graph
Given a graph with nodes 1 to 7 and edges: (1-2), (2-3), (4-5), (5-6), (6-4), (7), how many connected components does BFS find?
A4
B2
C3
D1
Attempts:
2 left
💡 Hint
Group nodes by connectivity and count groups.

Practice

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

Solution

  1. Step 1: Understand BFS role in connected components

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

    BFS does not directly find shortest paths between arbitrary nodes, max degree, or edge count in this context.
  3. Final Answer:

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

    BFS finds connected components [OK]
Hint: BFS visits all nodes in one connected group [OK]
Common Mistakes:
  • Confusing BFS with shortest path only
  • Thinking BFS counts edges or degrees
  • Mixing connected components with graph size
2. Which of the following Go code snippets correctly initializes a queue for BFS traversal?
easy
A. queue := []int{} // empty slice for BFS queue
B. queue := make(map[int]bool) // map used as queue
C. queue := 0 // integer used as queue
D. queue := "queue" // string used as queue"

Solution

  1. Step 1: Identify correct queue data structure for BFS

    BFS requires a queue to hold nodes; a slice of ints is a common and correct choice in Go.
  2. Step 2: Eliminate incorrect queue initializations

    Maps, integers, or strings cannot function as queues for BFS traversal.
  3. Final Answer:

    queue := []int{} // empty slice for BFS queue -> Option A
  4. Quick Check:

    Queue for BFS = slice of ints [OK]
Hint: Use slice of ints as queue in Go BFS [OK]
Common Mistakes:
  • Using map instead of slice for queue
  • Using integer or string as queue
  • Not initializing queue before BFS
3. Given the following graph adjacency list and BFS code, what is the output number of connected components?
graph := map[int][]int{
  0: {1},
  1: {0, 2},
  2: {1},
  3: {4},
  4: {3},
  5: {},
}

visited := make(map[int]bool)
count := 0
for node := range graph {
  if !visited[node] {
    queue := []int{node}
    visited[node] = true
    for len(queue) > 0 {
      current := queue[0]
      queue = queue[1:]
      for _, neighbor := range graph[current] {
        if !visited[neighbor] {
          visited[neighbor] = true
          queue = append(queue, neighbor)
        }
      }
    }
    count++
  }
}
fmt.Println(count)
medium
A. 3
B. 2
C. 1
D. 4

Solution

  1. Step 1: Identify connected components in the graph

    Nodes 0,1,2 form one component; nodes 3,4 form second; node 5 alone forms third.
  2. Step 2: BFS visits each component once, incrementing count

    Loop visits nodes 0,3,5 as unvisited starts, counting 3 components total.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    3 connected components = 3 [OK]
Hint: Count BFS starts on unvisited nodes [OK]
Common Mistakes:
  • Counting edges instead of components
  • Missing isolated nodes as components
  • Not marking visited nodes properly
4. The following BFS code for counting connected components has a bug. What is the error?
func countComponents(graph map[int][]int) int {
  visited := make(map[int]bool)
  count := 0
  for node := range graph {
    if visited[node] {
      queue := []int{node}
      visited[node] = true
      for len(queue) > 0 {
        current := queue[0]
        queue = queue[1:]
        for _, neighbor := range graph[current] {
          if !visited[neighbor] {
            visited[neighbor] = true
            queue = append(queue, neighbor)
          }
        }
      }
      count++
    }
  }
  return count
}
medium
A. The visited map is not initialized
B. The queue initialization is incorrect
C. The condition should be if !visited[node], not if visited[node]
D. The count variable is not incremented

Solution

  1. Step 1: Analyze the if condition for BFS start

    The code starts BFS only if visited[node] is true, which is wrong; it should start if node is not visited.
  2. Step 2: Understand impact on BFS traversal

    Because of wrong condition, BFS never starts, so count remains zero incorrectly.
  3. Final Answer:

    The condition should be if !visited[node], not if visited[node] -> Option C
  4. Quick Check:

    Start BFS on unvisited nodes [OK]
Hint: Start BFS only if node is unvisited [OK]
Common Mistakes:
  • Using visited[node] instead of !visited[node]
  • Not initializing visited map
  • Forgetting to increment count
5. You have a graph with nodes 0 to 6 and edges: (0-1), (1-2), (3-4), (5-6). Using BFS to find connected components, what is the count if node 7 is isolated and missing from the adjacency list? Choose the correct approach to count all components including isolated nodes.
hard
A. Count only nodes connected by edges
B. Include node 7 in the graph map with empty adjacency list before BFS
C. Ignore node 7 since it is not in adjacency list
D. Add node 7 as connected to node 0

Solution

  1. Step 1: Recognize isolated nodes must be in graph map

    To count isolated nodes as components, they must appear in the graph with empty adjacency lists.
  2. Step 2: Include node 7 with empty neighbors before BFS

    Adding node 7 ensures BFS visits it as a separate component.
  3. Final Answer:

    Include node 7 in the graph map with empty adjacency list before BFS -> Option B
  4. Quick Check:

    Isolated nodes need empty adjacency list [OK]
Hint: Add isolated nodes with empty lists to graph before BFS [OK]
Common Mistakes:
  • Ignoring isolated nodes not in adjacency list
  • Assuming isolated nodes are counted automatically
  • Connecting isolated nodes incorrectly
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