Shortest Path in Unweighted Graph Using BFS in DSA Javascript - Time & Space Complexity
We want to know how the time needed to find the shortest path in an unweighted graph grows as the graph gets bigger.
Specifically, how does the search process scale with more nodes and edges?
Analyze the time complexity of the following code snippet.
function shortestPathBFS(graph, start) {
const queue = [start];
const distances = { [start]: 0 };
while (queue.length > 0) {
const node = queue.shift();
for (const neighbor of graph[node]) {
if (distances[neighbor] === undefined) {
distances[neighbor] = distances[node] + 1;
queue.push(neighbor);
}
}
}
return distances;
}
This code finds the shortest distance from the start node to all other nodes using a breadth-first search.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node and checking its neighbors in the graph.
- How many times: Each node is visited once, and each edge is checked once during the search.
As the number of nodes and edges grows, the work grows roughly in proportion to their total count.
| Input Size (n nodes, m edges) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 25 checks (nodes + edges) |
| 100 nodes, 200 edges | About 300 checks |
| 1000 nodes, 5000 edges | About 6000 checks |
Pattern observation: The total operations grow roughly as the sum of nodes and edges, increasing linearly as the graph grows.
Time Complexity: O(n + m)
This means the time to find shortest paths grows linearly with the number of nodes plus edges in the graph.
[X] Wrong: "The BFS time depends only on the number of nodes, so it is O(n)."
[OK] Correct: BFS also checks all edges connected to nodes, so edges affect the time too, making it O(n + m).
Understanding BFS time complexity helps you explain how graph searches scale, a key skill in many coding challenges and real-world problems.
"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 DQuick Check:
BFS = shortest path in unweighted graph [OK]
- Confusing BFS with DFS for shortest path
- Thinking BFS finds longest path
- Assuming BFS counts total nodes only
Solution
Step 1: Identify BFS queue operations
BFS requires adding nodes at the end and removing from the front, which is a queue behavior.Step 2: Use Array methods for queue
JavaScript arrays support push (add end) and shift (remove front), perfect for BFS queue.Final Answer:
Array with push and shift methods -> Option BQuick Check:
Queue = Array push/shift [OK]
- Using Set as queue (no order guaranteed)
- Using Map for queue operations
- Using Object which has no order
const graph = {
0: [1, 2],
1: [0, 3],
2: [0, 3],
3: [1, 2, 4],
4: [3]
};
// BFS from node 0Solution
Step 1: Initialize distances and start BFS
Distance to start node 0 is 0. Neighbors 1 and 2 get distance 1.Step 2: Visit neighbors of 1 and 2
Node 3 is neighbor of 1 and 2, so distance is 2. Node 4 is neighbor of 3, distance 3.Final Answer:
[0, 1, 1, 2, 3] -> Option CQuick Check:
Distances = [0,1,1,2,3] [OK]
- Assigning wrong distances to neighbors
- Mixing up node indices
- Forgetting to update distance only once
function bfs(graph, start) {
const queue = [];
const distances = {};
queue.push(start);
distances[start] = 0;
while (queue.length > 0) {
const node = queue.pop();
for (const neighbor of graph[node]) {
if (!(neighbor in distances)) {
distances[neighbor] = distances[node] + 1;
queue.push(neighbor);
}
}
}
return distances;
}Solution
Step 1: Check queue operations in BFS
BFS requires FIFO order, so nodes must be removed from front using shift(), not pop() which removes from end.Step 2: Effect of using pop()
Using pop() makes it LIFO, turning BFS into DFS order, breaking shortest path logic.Final Answer:
Using pop() instead of shift() causes wrong BFS order -> Option AQuick Check:
Queue removal must be shift() for BFS [OK]
- Using pop() instead of shift() for queue
- Initializing distances incorrectly
- Using Set for queue which loses order
Solution
Step 1: Explore neighbors from node 0
Neighbors are 1 and 2, both distance 1.Step 2: From neighbors, explore node 3
Node 3 is neighbor of both 1 and 2, distance 2.Step 3: From node 3, go to 4 then 5
Node 4 distance 3, node 5 distance 4. The path via 1 is [0,1,3,4,5].Final Answer:
[0, 1, 3, 4, 5] -> Option AQuick Check:
Shortest path = [0,1,3,4,5] [OK]
- Choosing longer paths ignoring BFS order
- Skipping nodes in path
- Confusing edges and neighbors
Ready to prove it?
Pass the test and this pattern moves unknown
