Count connected components in graph
Last updated: March 19, 2026
Quick Overview
Given an undirected graph represented as an adjacency list, write a function to count the number of connected components in the graph. A connected component is a subset of the graph where there is a path between any two vertices in that subset. The function should return an integer representing the total number of connected components.
Splunk
March 19, 2026216
11
2,785 solved
Given an undirected graph represented as an adjacency list, write a function to count the number of connected components in the graph. A connected component is a subset of the graph where there is a path between any two vertices in that subset. The function should return an integer representing the total number of connected components.
Splunk uses this problem in the Onsite to evaluate your algorithmic thinking. They expect you to discuss multiple approaches, analyze trade-offs between them, and implement the optimal solution with clean, readable code.
What the Interviewer Expects
- Identify the correct data structure and algorithm for the problem
- Write clean, bug-free code with proper variable naming
- Analyze time and space complexity correctly
- Handle basic edge cases (empty input, single element)
- Communicate your thought process while coding
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you modify your solution to handle streaming input?
- How would your solution change if the input was sorted?
- How would you parallelize this solution?
- How would you test this solution thoroughly?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
To solve the problem of counting connected components in an undirected graph, we can utilize Depth-First Search (DFS) or Breadth-First Search (BFS) as our traversal method. The reason these algorithms...
Approach
- Initialize a
visitedset to keep track of visited nodes. - Initialize a
component_countvariable to zero to count the connected components. - Iterate through each vertex in the graph:
...