BFS traversal and applications in Data Structures Theory - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time needed for BFS traversal grows as the graph gets bigger.
Specifically, how does BFS handle more nodes and edges in a graph?
Analyze the time complexity of the following BFS traversal code.
function BFS(graph, startNode) {
let queue = []
let visited = new Set()
queue.push(startNode)
visited.add(startNode)
while (queue.length > 0) {
let node = queue.shift()
for (let neighbor of graph[node]) {
if (!visited.has(neighbor)) {
visited.add(neighbor)
queue.push(neighbor)
}
}
}
}
This code visits all nodes reachable from the startNode using a queue, exploring neighbors level by level.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node and checking its neighbors.
- How many times: Each node is enqueued and dequeued once; each edge is checked once.
As the number of nodes and edges grows, BFS visits each node once and checks all edges once.
| 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: Operations grow roughly in proportion to nodes plus edges.
Time Complexity: O(n + m)
This means BFS takes time proportional to the number of nodes plus the number of edges in the graph.
[X] Wrong: "BFS always takes time proportional to n squared because it checks all pairs of nodes."
[OK] Correct: BFS only checks edges that actually exist, not all pairs of nodes, so it depends on edges, not all possible pairs.
Understanding BFS time complexity helps you explain how graph algorithms scale and why BFS is efficient for many problems.
"What if the graph is represented as an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
BFS (Breadth-First Search) traversal of a graph?Solution
Step 1: Understand BFS traversal method
BFS explores nodes level by level, which requires processing nodes in the order they are discovered.Step 2: Identify the suitable data structure
A queue follows First-In-First-Out (FIFO) order, perfect for level-wise exploration in BFS.Final Answer:
Queue -> Option AQuick Check:
BFS uses a queue = Queue [OK]
- Confusing BFS with DFS which uses a stack
- Thinking BFS uses a priority queue
- Assuming BFS uses a hash map as main structure
Solution
Step 1: Understand when to mark nodes visited in BFS
Nodes should be marked visited when they are enqueued to prevent multiple enqueues of the same node.Step 2: Identify correct marking method
Adding nodes to a visited set immediately when enqueued ensures no duplicates in the queue.Final Answer:
Add node to a visited set or list immediately when enqueued -> Option BQuick Check:
Mark visited on enqueue = Add node to a visited set or list immediately when enqueued [OK]
- Marking nodes visited only after dequeuing
- Using a stack instead of a visited set
- Not marking nodes visited at all
0 - 1, 0 - 2, 1 - 3, 2 - 3If BFS starts at node 0, what is the order of nodes visited?
Solution
Step 1: Start BFS from node 0
Enqueue 0, visited order starts with 0.Step 2: Enqueue neighbors of 0 in order
Neighbors are 1 and 2, enqueue 1 then 2.Step 3: Dequeue 1 and enqueue its neighbor 3
3 is neighbor of 1, enqueue 3.Step 4: Dequeue 2, neighbor 3 already visited
No new nodes added.Step 5: Dequeue 3, no new neighbors
Traversal ends.Final Answer:
[0, 1, 2, 3] -> Option AQuick Check:
BFS order = [0, 1, 2, 3] [OK]
- Visiting neighbors in wrong order
- Adding nodes multiple times
- Starting BFS from wrong node
visited = set()
queue = [start]
visited.add(start)
while queue:
node = queue.pop()
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)Solution
Step 1: Analyze queue operations
pop() without argument removes last element, making it LIFO (stack), not FIFO (queue).Step 2: Understand BFS requires FIFO
BFS needs to remove from front (pop(0)) to process nodes level by level.Final Answer:
Using pop() removes from the end, causing DFS behavior -> Option DQuick Check:
pop() without index = DFS, not BFS [OK]
- Using pop() instead of pop(0)
- Forgetting to mark start node visited
- Confusing stack and queue roles
Solution
Step 1: Understand BFS finds shortest path length
BFS explores nodes level by level, so the first time B is found is shortest path length.Step 2: Track path by storing parents
When a node is enqueued, record which node led to it (its parent). After BFS, backtrack from B to A using parents.Final Answer:
Store each node's parent when enqueuing it, then backtrack from B to A -> Option CQuick Check:
Parent tracking + backtrack = shortest path [OK]
- Using stack instead of queue for BFS
- Marking visited too late causing duplicates
- Running BFS twice unnecessarily
