Find connected components in graph
Last updated: December 13, 2025
Quick Overview
Given an undirected graph represented as an adjacency list, write a function to find all connected components in the graph. The function should return a list of lists, where each inner list contains the nodes of a connected component. The input will be a dictionary where keys are node identifiers and values are lists of adjacent nodes.
Square/Block
December 13, 20252
3
3,504 solved
Given an undirected graph represented as an adjacency list, write a function to find all connected components in the graph. The function should return a list of lists, where each inner list contains the nodes of a connected component. The input will be a dictionary where keys are node identifiers and values are lists of adjacent nodes.
Square/Block 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 parallelize this solution?
- How would you test this solution thoroughly?
- Can you solve this in a single pass?
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
The problem requires us to find all connected components in an undirected graph represented as an adjacency list. A connected component is a subset of the graph where there exists a path between any t...
Approach
- Initialize a visited set to keep track of all the nodes we've explored.
- Iterate through each node in the adjacency list. If the node has not been visited, initiate a new DFS/BFS to exp...