Find connected components in matrix
Last updated: February 28, 2026
Quick Overview
Given a 2D matrix consisting of 0s and 1s, write a function to find and return all connected components of 1s, where connectivity is defined as horizontal or vertical adjacency. The output should be a list of lists, where each inner list contains the coordinates of the cells that form a connected component.
Microsoft
February 28, 20269
10
4,058 solved
Given a 2D matrix consisting of 0s and 1s, write a function to find and return all connected components of 1s, where connectivity is defined as horizontal or vertical adjacency. The output should be a list of lists, where each inner list contains the coordinates of the cells that form a connected component.
This coding problem is frequently asked during Take-home Project at Microsoft. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Microsoft expects candidates to write production-quality code, not just solve the puzzle.
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
- What happens if the input contains duplicates?
- What if the input doesn't fit in memory?
- How would you modify your solution to handle streaming input?
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 finding connected components of 1s in a 2D matrix, we can utilize Depth-First Search (DFS) or Breadth-First Search (BFS). The reason DFS applies here is that it allows us to ex...
Approach
- Initialize a list to hold the connected components.
- Create a
visitedmatrix to keep track of cells that have already been explored. - Iterate over each cell in the matrix. If a cell contains ...
Submit Your Answer
Microsoft Machine Learning Engineer Interview Guide
Interview process, tips, and preparation timeline