Shortest Path in Unweighted Graph Using BFS in DSA Go - Time & Space Complexity
We want to know how long it takes to find the shortest path in an unweighted graph using BFS.
Specifically, how the time grows as the graph gets bigger.
Analyze the time complexity of the following code snippet.
func shortestPathBFS(graph map[int][]int, start, target int) int {
visited := make(map[int]bool)
queue := []int{start}
distance := make(map[int]int)
distance[start] = 0
visited[start] = true
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
if node == target {
return distance[node]
}
for _, neighbor := range graph[node] {
if !visited[neighbor] {
visited[neighbor] = true
distance[neighbor] = distance[node] + 1
queue = append(queue, neighbor)
}
}
}
return -1
}
This code finds the shortest path length from start to target in an unweighted graph using BFS.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node and checking its neighbors.
- How many times: Each node and each edge is processed at most once.
As the graph grows, the algorithm visits more nodes and edges.
| Input Size (n nodes, m edges) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 25 operations (nodes + edges) |
| 100 nodes, 200 edges | About 300 operations |
| 1000 nodes, 5000 edges | About 6000 operations |
Pattern observation: The operations grow roughly with the sum of nodes and edges.
Time Complexity: O(n + m)
This means the time grows linearly with the number of nodes plus edges in the graph.
[X] Wrong: "BFS takes O(n²) time because it uses nested loops."
[OK] Correct: BFS visits each node and edge only once, so it does not repeat work for the same parts, making it linear in nodes and edges.
Understanding BFS time complexity helps you explain efficient graph traversal clearly and confidently in interviews.
"What if the graph was represented as an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
Solution
Step 1: Understand BFS traversal
BFS explores nodes level by level starting from the source node, visiting all neighbors before moving deeper.Step 2: BFS finds shortest paths in unweighted graphs
Because BFS visits nodes in order of increasing distance, the first time it reaches a node is via the shortest path.Final Answer:
The shortest path from a start node to all other nodes -> Option CQuick Check:
BFS = Shortest path in unweighted graph [OK]
- Confusing BFS with DFS for shortest path
- Thinking BFS finds longest paths
- Mixing BFS with minimum spanning tree algorithms
Solution
Step 1: Identify queue requirements in BFS
BFS requires a FIFO (first-in, first-out) structure to process nodes in order.Step 2: Use slice as queue in Go
Slices can be used to append at the end and remove from the front, effectively acting as a queue.Final Answer:
slice -> Option DQuick Check:
Queue for BFS = slice [OK]
- Using map which is unordered
- Using struct without queue logic
- Using channel without concurrency context
graph := [][]int{
{1, 2},
{0, 3},
{0, 3},
{1, 2, 4},
{3},
}
Solution
Step 1: Initialize distances and start BFS from node 0
Distance[0] = 0, others = -1 (unvisited). Queue starts with 0.Step 2: Visit neighbors level by level
From 0: neighbors 1 and 2 get distance 1. From 1 and 2: neighbor 3 gets distance 2. From 3: neighbor 4 gets distance 3.Final Answer:
[0, 1, 1, 2, 3] -> Option AQuick Check:
Distances = [0,1,1,2,3] [OK]
- Assigning wrong distances to neighbors
- Confusing node indices
- Not initializing distances properly
func BFS(graph [][]int, start int) []int {
dist := make([]int, len(graph))
for i := range dist {
dist[i] = -1
}
dist[start] = 0
queue := []int{start}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
for _, neighbor := range graph[node] {
if dist[neighbor] == 0 {
dist[neighbor] = dist[node] + 1
queue = append(queue, neighbor)
}
}
}
return dist
}
Solution
Step 1: Check distance initialization and visit condition
Distances start at -1 for unvisited nodes. The condition to visit neighbors should check for -1, not 0.Step 2: Fix condition to correctly detect unvisited neighbors
Change if dist[neighbor] == 0 to if dist[neighbor] == -1 to avoid skipping nodes.Final Answer:
dist[neighbor] == 0 should be dist[neighbor] == -1 -> Option AQuick Check:
Check unvisited with -1, not 0 [OK]
- Checking visited nodes incorrectly
- Initializing distances with zero
- Modifying queue incorrectly
0-1, 0-2, 1-3, 2-3, 3-4, 4-5What is the shortest path from node 0 to node 5 using BFS?
Solution
Step 1: Explore neighbors from node 0
From 0, neighbors are 1 and 2. Both at distance 1.Step 2: Explore neighbors from 1 and 2
From 1: neighbor 3; from 2: neighbor 3. Node 3 is at distance 2.Step 3: Explore neighbors from 3, then 4, then 5
From 3: neighbor 4 (distance 3). From 4: neighbor 5 (distance 4). Path is 0->1->3->4->5 or 0->2->3->4->5.Step 4: Choose shortest path with earliest discovery
BFS discovers 1 before 2, so path is [0,1,3,4,5].Final Answer:
[0, 1, 3, 4, 5] -> Option BQuick Check:
Shortest path BFS = [0,1,3,4,5] [OK]
- Choosing longer paths ignoring BFS order
- Skipping nodes in path reconstruction
- Confusing path with distance array
Ready to prove it?
Pass the test and this pattern moves unknown
