DFS on matrix

Last updated: May 5, 2026

Quick Overview

Implement a Depth-First Search (DFS) algorithm to traverse a given 2D matrix. The matrix may contain obstacles represented by specific values, and your task is to find all connected components of valid cells, returning their coordinates as output. Ensure your solution handles edge cases such as empty matrices and matrices with no valid cells.

Coinbase
Coding & Algorithms
Machine Learning Engineer
Coinbase
May 5, 2026
Machine Learning Engineer
Technical Screen
Coding & Algorithms
Easy

286

4

1,579 solved


Implement a Depth-First Search (DFS) algorithm to traverse a given 2D matrix. The matrix may contain obstacles represented by specific values, and your task is to find all connected components of valid cells, returning their coordinates as output. Ensure your solution handles edge cases such as empty matrices and matrices with no valid cells.

Coinbase uses this problem in the Technical Screen 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
Tree structures and recursion
Hash maps and frequency counting
Data structure selection and trade-offs
Graph algorithms and traversal
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you test this solution thoroughly?
  • How would you parallelize this solution?
  • Can you solve this in a single pass?
  • What happens if the input contains duplicates?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

In this problem, we are asked to perform a Depth-First Search (DFS) on a 2D matrix to find all connected components of valid cells. A connected component consists of cells that are valid and adjacent ...

Approach
  1. Initialize Variables: Start by creating a set to keep track of visited cells and an empty list to hold the coordinates of connected components.

  2. Iterate Through the Matrix: Loop through ...


Submit Your Answer
Markdown supported

Related Questions