BFS Breadth First Search on Graph in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to explore a graph grows as the graph gets bigger using BFS.
How does BFS's work change when the graph has more nodes and edges?
Analyze the time complexity of the following code snippet.
function bfs(graph: Map<number, number[]>, start: number): number[] {
const visited = new Set<number>();
const queue: number[] = [];
const result: number[] = [];
queue.push(start);
visited.add(start);
while (queue.length > 0) {
const node = queue.shift()!;
result.push(node);
for (const neighbor of graph.get(node) || []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
return result;
}
This code explores all nodes reachable from the start node using BFS, visiting neighbors level by level.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs as long as there are nodes in the queue, processing each node once.
- How many times: Each node is visited once, and each edge is checked once when exploring neighbors.
As the graph grows, BFS visits every node and checks every edge connected to those nodes.
| Input Size (n nodes, m edges) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 10 node visits + 15 edge checks = 25 operations |
| 100 nodes, 200 edges | About 100 node visits + 200 edge checks = 300 operations |
| 1000 nodes, 5000 edges | About 1000 node visits + 5000 edge checks = 6000 operations |
Pattern observation: The work grows roughly in proportion to the number of nodes plus edges.
Time Complexity: O(n + m)
This means BFS takes time proportional to the total number of nodes plus edges in the graph.
[X] Wrong: "BFS always takes O(n²) time because it uses nested loops."
[OK] Correct: BFS visits each node and edge only once, so it does not repeatedly check all pairs; it scales with nodes plus edges, not their square.
Understanding BFS time complexity helps you explain how graph searches work efficiently, a key skill for many coding challenges and real-world problems.
"What if the graph is represented as an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
Solution
Step 1: Understand BFS traversal method
BFS explores nodes level by level, so it needs a structure that processes nodes in the order they are discovered.Step 2: Identify the data structure used
A queue follows First-In-First-Out (FIFO) order, which matches BFS's level order traversal.Final Answer:
A queue to process nodes level by level -> Option DQuick Check:
BFS uses a queue = A [OK]
- Confusing BFS with DFS which uses a stack
- Thinking BFS uses a priority queue
- Assuming BFS only uses a visited set without a queue
Solution
Step 1: Recognize TypeScript array initialization
To create a queue using an array, declare an array with type annotation and initialize it empty.Step 2: Check each option
const queue: number[] = []; correctly declares an empty number array. const queue = new Queue<number>(); uses a class Queue which is not built-in. let queue = {}; initializes an object, not a queue. var queue = new ArrayQueue(); uses a non-existent ArrayQueue.Final Answer:
const queue: number[] = []; -> Option BQuick Check:
Array queue syntax = A [OK]
- Using undefined classes like Queue without import
- Initializing queue as an object {} instead of array
- Using var instead of const or let (less preferred)
const graph = {
0: [1, 2],
1: [3],
2: [3],
3: []
};
Solution
Step 1: Start BFS from node 0
Visit node 0 first, then enqueue its neighbors 1 and 2.Step 2: Visit neighbors in queue order
Dequeue 1, visit it, enqueue its neighbor 3. Then dequeue 2, visit it, enqueue 3 again but already visited. Finally, dequeue 3.Final Answer:
[0, 1, 2, 3] -> Option AQuick Check:
BFS order = [0, 1, 2, 3] [OK]
- Visiting neighbors in wrong order
- Visiting node 3 twice
- Starting BFS from wrong node
function bfs(graph: Record, start: number) {
const queue: number[] = [start];
const visited = new Set<number>();
while (queue.length > 0) {
const node = queue.shift();
if (!visited.has(node)) {
visited.add(node);
for (const neighbor of graph[node]) {
queue.push(neighbor);
}
}
}
return Array.from(visited);
}Solution
Step 1: Analyze queue.shift() usage
queue.shift() returns number | undefined. If queue is empty, node can be undefined, causing errors when accessing graph[node].Step 2: Identify missing check for undefined
Code should check if node is undefined before using it. Without this, runtime error can occur.Final Answer:
queue.shift() can return undefined, causing errors -> Option AQuick Check:
Check for undefined after shift = B [OK]
- Ignoring possible undefined from shift()
- Assuming visited set is wrong when it is correct
- Thinking neighbors are not added when they are
const graph = {
0: [1, 2],
1: [3],
2: [3, 4],
3: [4],
4: []
};
Which BFS modification helps find the shortest path length correctly?Solution
Step 1: Understand BFS for shortest path
BFS finds shortest paths in unweighted graphs by exploring neighbors level by level.Step 2: Track distance when visiting nodes
Maintain a distance map or array to record the number of edges from start node to each node when first visited.Final Answer:
Track distance for each node when first visited -> Option CQuick Check:
Distance tracking in BFS = D [OK]
- Using stack breaks BFS order
- Visiting nodes multiple times wastes time
- Ignoring visited set causes infinite loops
Ready to prove it?
Pass the test and this pattern moves unknown
