Count connected components in matrix
Last updated: September 19, 2025
Quick Overview
Given a binary matrix where 1s represent land and 0s represent water, write a function to count the number of connected components of land. Two land cells are considered connected if they are adjacent horizontally or vertically. The function should return an integer representing the total number of connected components in the matrix.
Figma
September 19, 202536
6
1,499 solved
Given a binary matrix where 1s represent land and 0s represent water, write a function to count the number of connected components of land. Two land cells are considered connected if they are adjacent horizontally or vertically. The function should return an integer representing the total number of connected components in the matrix.
This coding problem is frequently asked during Phone Screen at Figma. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Figma expects candidates to write production-quality code, not just solve the puzzle.
What the Interviewer Expects
- Quickly identify the optimal approach and its theoretical basis
- Handle complex algorithm design with multiple interacting components
- Write concise, elegant code under time pressure
- Prove correctness of your approach and discuss alternative solutions
- Optimize beyond the obvious: discuss constant factor improvements
- Address follow-up variations and explain how the solution generalizes
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?
- Can you optimize the space complexity of your solution?
- What if the input doesn't fit in memory?
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 count connected components of land (1s) in a binary matrix where connectivity is defined in terms of horizontal and vertical adjacency. This is a graph traversal problem whe...
Approach
- Initialize a counter
countto 0 to track the number of connected components. - Iterate through each cell in the matrix:
- If a cell contains 1 (land) and has not been visited yet, increment `...