Connected Components Using BFS in DSA Typescript - Time & Space Complexity
We want to understand how long it takes to find all connected parts in a graph using BFS.
How does the time grow as the graph gets bigger?
Analyze the time complexity of the following code snippet.
function connectedComponents(graph: Map): number {
const visited = new Set();
let count = 0;
for (const node of graph.keys()) {
if (!visited.has(node)) {
bfs(node, graph, visited);
count++;
}
}
return count;
}
function bfs(start: number, graph: Map, visited: Set) {
const queue: number[] = [start];
visited.add(start);
while (queue.length > 0) {
const node = queue.shift()!;
for (const neighbor of graph.get(node) || []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
}
This code counts how many connected groups are in a graph by visiting nodes using BFS.
- Primary operation: Visiting each node and its neighbors once using BFS.
- How many times: Each node and edge is checked once during the BFS traversals.
As the graph grows, the BFS visits every node and edge once.
| Input Size (n nodes, e edges) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 25 visits (nodes + edges) |
| 100 nodes, 200 edges | About 300 visits |
| 1000 nodes, 3000 edges | About 4000 visits |
Pattern observation: The work grows roughly with the number of nodes plus edges.
Time Complexity: O(n + e)
This means the time grows linearly with the total nodes and edges in the graph.
[X] Wrong: "The BFS runs in O(n²) because it has nested loops."
[OK] Correct: Each edge and node is visited only once, so the total work is linear, not quadratic.
Understanding BFS time complexity helps you explain graph traversal efficiency clearly and confidently.
"What if the graph was represented as an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
connected components mean in an undirected graph when using BFS?Solution
Step 1: Understand connected components in undirected graphs
Connected components are sets of nodes where each node can be reached from any other node in the same set by following edges.Step 2: Relate BFS to connected components
BFS explores all nodes reachable from a starting node, thus identifying one connected component at a time.Final Answer:
Groups of nodes where each node is reachable from any other node in the same group -> Option AQuick Check:
Connected components = reachable groups [OK]
- Confusing connected components with shortest paths
- Thinking isolated nodes are connected components with edges
- Mixing cycles with connected components
Solution
Step 1: Identify correct TypeScript array initialization
In TypeScript, a queue for BFS can be implemented using an array:const queue: number[] = [];initializes an empty number array.Step 2: Check other options for correctness
Options A and B use undefined classesArrayQueueandQueuewhich are not built-in. var queue = []; queue.push(1); usesvarwhich is discouraged and lacks type annotation.Final Answer:
const queue: number[] = []; -> Option BQuick Check:
Array queue initialization = const queue: number[] = [] [OK]
- Using undefined queue classes
- Using var instead of let/const
- Not typing the queue array
const graph = {
0: [1],
1: [0, 2],
2: [1],
3: [4],
4: [3]
};
function bfsComponents(graph: {[key: number]: number[]}): number[][] {
const visited = new Set<number>();
const components: number[][] = [];
for (const node in graph) {
const n = Number(node);
if (!visited.has(n)) {
const queue: number[] = [n];
const component: number[] = [];
visited.add(n);
while (queue.length > 0) {
const current = queue.shift()!;
component.push(current);
for (const neighbor of graph[current]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
components.push(component);
}
}
return components;
}
console.log(bfsComponents(graph));Solution
Step 1: Analyze graph structure
The graph has two connected components: nodes 0,1,2 connected together and nodes 3,4 connected together.Step 2: Trace BFS traversal
Starting from node 0, BFS visits 0, then 1, then 2. Then from node 3, BFS visits 3 and 4. So components are [[0,1,2],[3,4]].Final Answer:
[[0, 1, 2], [3, 4]] -> Option DQuick Check:
Two connected groups = [[0,1,2],[3,4]] [OK]
- Assuming all nodes are one component
- Splitting connected nodes incorrectly
- Confusing node order in output
function bfsComponents(graph: {[key: number]: number[]}): number[][] {
const visited = new Set<number>();
const components: number[][] = [];
for (const node in graph) {
const n = Number(node);
if (!visited.has(n)) {
const queue: number[] = [n];
const component: number[] = [];
while (queue.length > 0) {
const current = queue.shift()!;
component.push(current);
for (const neighbor of graph[current]) {
if (!visited.has(neighbor)) {
queue.push(neighbor);
visited.add(neighbor);
}
}
}
components.push(component);
}
}
return components;
}Solution
Step 1: Check visited node addition timing
Visited nodes should be marked as visited before pushing to queue to avoid duplicates.Step 2: Identify the bug in code
In the code,queue.push(neighbor)happens beforevisited.add(neighbor), which can cause the same neighbor to be pushed multiple times if visited check is delayed.Final Answer:
Visited nodes are added after pushing to queue, causing duplicates -> Option CQuick Check:
Mark visited before queue push to avoid duplicates [OK]
- Adding visited after queue push
- Not adding visited at all
- Forgetting to push neighbors
const graph = {
0: [1],
1: [0, 2],
2: [1],
3: [4],
4: [3],
5: []
};
// BFS connected components function returns array of components
What is the correct connected components output?Solution
Step 1: Analyze graph edges and isolated nodes
Nodes 0,1,2 form one connected component; nodes 3,4 form another; node 5 is isolated with no edges.Step 2: Understand BFS output for connected components
BFS will find three components: [0,1,2], [3,4], and [5] as a single-node component.Final Answer:
[[0, 1, 2], [3, 4], [5]] -> Option AQuick Check:
Isolated nodes form their own components [OK]
- Ignoring isolated nodes
- Merging all nodes into one component
- Misgrouping connected nodes
Ready to prove it?
Pass the test and this pattern moves unknown
