Bird
Raised Fist0
DSA Goprogramming~20 mins

BFS Breadth First Search on Graph in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
BFS Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of BFS traversal on a simple graph
What is the output of the BFS traversal starting from node 0 in the given graph?
DSA Go
package main

import (
	"fmt"
)

func bfs(graph map[int][]int, start int) []int {
	visited := make(map[int]bool)
	queue := []int{start}
	visited[start] = true
	order := []int{}

	for len(queue) > 0 {
		current := queue[0]
		queue = queue[1:]
		order = append(order, current)

		for _, neighbor := range graph[current] {
			if !visited[neighbor] {
				visited[neighbor] = true
				queue = append(queue, neighbor)
			}
		}
	}
	return order
}

func main() {
	graph := map[int][]int{
		0: {1, 2},
		1: {2},
		2: {0, 3},
		3: {3},
	}
	result := bfs(graph, 0)
	fmt.Println(result)
}
A[0 1 3 2]
B[0 2 1 3]
C[0 1 2 3]
D[0 3 2 1]
Attempts:
2 left
💡 Hint
Remember BFS visits neighbors level by level, starting from the start node.
🧠 Conceptual
intermediate
1:30remaining
BFS queue behavior on a graph with cycles
In BFS, why is it important to mark nodes as visited before adding them to the queue when the graph contains cycles?
ATo avoid adding the same node multiple times and prevent infinite loops.
BTo prioritize nodes with higher values.
CTo allow revisiting nodes multiple times for accuracy.
DTo ensure nodes are processed in reverse order.
Attempts:
2 left
💡 Hint
Think about what happens if a node is added multiple times in a cycle.
🔧 Debug
advanced
2:00remaining
Identify the bug in BFS implementation
What error will occur when running this BFS code on a graph with nodes 0 to 3?
DSA Go
func bfsBug(graph map[int][]int, start int) []int {
	visited := make(map[int]bool)
	queue := []int{start}
	order := []int{}

	for len(queue) > 0 {
		current := queue[0]
		queue = queue[1:]
		order = append(order, current)

		for _, neighbor := range graph[current] {
			if !visited[neighbor] {
				queue = append(queue, neighbor)
			}
		}
	}
	return order
}
AInfinite loop because visited nodes are never marked.
BCompilation error due to missing return statement.
CRuntime panic due to nil map access.
DCorrect output with no errors.
Attempts:
2 left
💡 Hint
Check if nodes are marked visited anywhere.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in BFS code snippet
Which option contains the syntax error preventing BFS code from compiling?
DSA Go
func bfsSyntax(graph map[int][]int, start int) []int {
	visited := make(map[int]bool)
	queue := []int{start}
	visited[start] = true
	order := []int{}

	for len(queue) > 0 {
		current := queue[0]
		queue = queue[1:]
		order = append(order, current)

		for _, neighbor := range graph[current] {
			if !visited[neighbor] {
				visited[neighbor] = true
				queue = append(queue, neighbor)
			}
		}
	}
	return order
}
Afunc bfsSyntax(graph map[int][]int, start int) []int { ... // missing closing brace
Bfunc bfsSyntax(graph map[int][]int start int) []int { ... } // missing comma
Cfunc bfsSyntax(graph map[int][]int, start int) []int { ... } // correct syntax
Dfunc bfsSyntax(graph map[int][]int, start int) []int { visited := make(map[int]bool) queue := []int{start} visited[start] = true order := []int{} for len(queue) > 0 { current := queue[0] queue = queue[1:] order = append(order, current) for _, neighbor := range graph[current] { if !visited[neighbor] { visited[neighbor] = true queue = append(queue, neighbor) } } } return order
Attempts:
2 left
💡 Hint
Check function parameter list syntax carefully.
🚀 Application
expert
2:30remaining
BFS shortest path length in unweighted graph
Given the BFS function below, what is the shortest path length from node 0 to node 4 in the graph? Return -1 if no path exists.
DSA Go
package main

import (
	"fmt"
)

func bfsShortestPath(graph map[int][]int, start, target int) int {
	visited := make(map[int]bool)
	queue := []int{start}
	visited[start] = true
	distance := make(map[int]int)
	distance[start] = 0

	for len(queue) > 0 {
		current := queue[0]
		queue = queue[1:]

		if current == target {
			return distance[current]
		}

		for _, neighbor := range graph[current] {
			if !visited[neighbor] {
				visited[neighbor] = true
				queue = append(queue, neighbor)
				distance[neighbor] = distance[current] + 1
			}
		}
	}
	return -1
}

func main() {
	graph := map[int][]int{
		0: {1, 2},
		1: {2, 3},
		2: {3},
		3: {4},
		4: {},
	}
	result := bfsShortestPath(graph, 0, 4)
	fmt.Println(result)
}
A2
B4
C-1
D3
Attempts:
2 left
💡 Hint
BFS finds shortest paths in unweighted graphs by levels.

Practice

(1/5)
1. What is the main purpose of BFS (Breadth First Search) on a graph?
easy
A. To sort nodes in descending order
B. To find the shortest path using depth-first traversal
C. To explore all nodes level by level starting from a source node
D. To find cycles in a graph using recursion

Solution

  1. Step 1: Understand BFS traversal

    BFS explores nodes by visiting all neighbors of a node before moving to the next level.
  2. Step 2: Compare BFS with other traversals

    Unlike DFS, BFS uses a queue to explore nodes level by level, which helps in shortest path problems.
  3. Final Answer:

    To explore all nodes level by level starting from a source node -> Option C
  4. Quick Check:

    BFS = Level-wise exploration [OK]
Hint: BFS uses a queue to explore nodes level by level [OK]
Common Mistakes:
  • Confusing BFS with DFS
  • Thinking BFS uses recursion
  • Assuming BFS sorts nodes
2. Which of the following Go code snippets correctly initializes a queue for BFS traversal?
easy
A. queue := []int{} // empty slice as queue
B. queue := make(map[int]bool) // map as queue
C. queue := 0 // integer as queue
D. queue := make(chan int) // channel as queue

Solution

  1. Step 1: Identify data structure for BFS queue

    BFS requires a FIFO structure; a slice can be used as a queue in Go.
  2. Step 2: Check each option

    queue := []int{} // empty slice as queue uses a slice which can enqueue and dequeue elements. queue := make(map[int]bool) // map as queue is a map, not suitable as queue. queue := 0 // integer as queue is an int, not a queue. queue := make(chan int) // channel as queue is a channel, which can be used but requires goroutines and is complex.
  3. Final Answer:

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

    Slice as queue = queue := []int{} // empty slice as queue [OK]
Hint: Use slice for queue in BFS, not map or int [OK]
Common Mistakes:
  • Using map instead of slice for queue
  • Using int variable as queue
  • Confusing channels with simple queue
3. What is the output of the following Go BFS traversal code on the graph below?

Graph edges:
0 -> 1, 2
1 -> 2
2 -> 0, 3
3 -> 3

package main
import "fmt"
func bfs(graph map[int][]int, start int) []int {
    visited := make(map[int]bool)
    queue := []int{start}
    order := []int{}
    visited[start] = true
    for len(queue) > 0 {
        node := queue[0]
        queue = queue[1:]
        order = append(order, node)
        for _, neighbor := range graph[node] {
            if !visited[neighbor] {
                visited[neighbor] = true
                queue = append(queue, neighbor)
            }
        }
    }
    return order
}
func main() {
    graph := map[int][]int{
        0: {1, 2},
        1: {2},
        2: {0, 3},
        3: {3},
    }
    fmt.Println(bfs(graph, 2))
}
medium
A. [2, 0, 1, 3]
B. [2, 0, 3, 1]
C. [2, 3, 0, 1]
D. [2, 1, 0, 3]

Solution

  1. Step 1: Start BFS from node 2

    Initialize queue=[2], visited={2}. Dequeue 2, enqueue neighbors 0 and 3. order=[2]
  2. Step 2: Process nodes in queue

    Queue=[0,3]. Dequeue 0, enqueue neighbor 1 (2 already visited). order=[2,0]. Queue=[3,1]. Dequeue 3, neighbor 3 already visited. order=[2,0,3]. Queue=[1]. Dequeue 1, neighbor 2 visited. order=[2,0,3,1]. Queue empty.
  3. Final Answer:

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

    BFS order from 2 = [2,0,3,1] [OK]
Hint: Track queue and visited sets stepwise [OK]
Common Mistakes:
  • Not marking visited before enqueue
  • Wrong order of neighbors enqueued
  • Confusing BFS with DFS order
4. Identify the bug in the following BFS Go code snippet and select the correct fix.

func bfs(graph map[int][]int, start int) []int {
    visited := make(map[int]bool)
    queue := []int{start}
    order := []int{}
    for len(queue) > 0 {
        node := queue[0]
        queue = queue[1:]
        order = append(order, node)
        for _, neighbor := range graph[node] {
            if !visited[neighbor] {
                queue = append(queue, neighbor)
                visited[neighbor] = true
            }
        }
    }
    return order
}
medium
A. Mark start node as visited before loop
B. Initialize order slice with capacity
C. Use a stack instead of queue
D. Remove visited map entirely

Solution

  1. Step 1: Check visited marking for start node

    The code never marks the start node as visited before starting, so it may revisit it.
  2. Step 2: Fix by marking start visited before loop

    Adding visited[start] = true before the loop prevents revisiting the start node and infinite loops.
  3. Final Answer:

    Mark start node as visited before loop -> Option A
  4. Quick Check:

    Start visited before loop = Mark start node as visited before loop [OK]
Hint: Always mark start visited before BFS loop [OK]
Common Mistakes:
  • Marking visited after enqueue
  • Using stack instead of queue
  • Ignoring visited map
5. Given a directed graph represented as adjacency list, how can BFS be adapted to find the shortest path length from a start node to a target node? Choose the best approach.
hard
A. Use BFS but enqueue nodes multiple times to find shortest path
B. Use DFS and backtrack to find all paths, then pick shortest
C. Use BFS but ignore visited nodes to explore all paths
D. Use BFS with a distance map to track levels from start, stop when target found

Solution

  1. Step 1: Understand BFS for shortest path

    BFS explores nodes level by level, so the first time target is reached is the shortest path.
  2. Step 2: Use a distance map to track levels

    Maintain a map to record distance from start for each node. When target is dequeued, return its distance.
  3. Final Answer:

    Use BFS with a distance map to track levels from start, stop when target found -> Option D
  4. Quick Check:

    BFS + distance map = shortest path [OK]
Hint: Track distance in BFS, stop at target [OK]
Common Mistakes:
  • Using DFS for shortest path in unweighted graph
  • Ignoring visited nodes causing infinite loops
  • Enqueuing nodes multiple times unnecessarily
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