Interview's MateDSA Visualizer
Interview's Mate

DSA Visualizer

Learn by watching algorithms run

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
All topics
PROBLEM-SOLVING TECHNIQUES

Depth-First Search

Go as deep as possible down one path before backing up.

Intermediate9 problems2 interactive subtopicsO(rows × cols) time and space
Practice in AI DSA
WalkthroughOverviewRecognize itMistakes & edge casesKnowledge check (3)Practice
Algorithms & custom examples (2)Open in full playground →
STEP 1/5Land at (0, 0)
land at (0, 0) · count = 1
1
1
0
0
1
0
0
0
1
  • current
  • land
  • water
  • ruled out
  • active this step
Space Play←→ StepR Replay
1 / 5
PYTHONgrid = [["1","1","0"], ["0","1","0"], ["0","0","1"]]
1def num_islands(grid):
2 rows, cols = len(grid), len(grid[0])
3 def sink(r, c):
4 if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] != "1":
5 return
6 grid[r][c] = "0"
7 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
8 sink(r + dr, c + dc)
9 count = 0
10 for r in range(rows):
11 for c in range(cols):
12 if grid[r][c] == "1":
▶13 count += 1
14 sink(r, c)
15 return count
STEP 1 OF 5Setup

Land at (0, 0)

A new island, so count becomes 1 and DFS starts sinking it.

VARIABLES

cell
(0, 0)
count
1
02

Intuition & complexity

The core mental model, trade-offs, and Big-O cost.

What it is

DFS follows one branch to its end, then returns to the most recent choice. It uses recursion or an explicit stack, plus a visited set.

Why it matters

Connectivity, cycle detection, path existence and tree problems are often simplest as DFS.

Think of it like this

Exploring a cave: follow one tunnel to its end before trying the next.

Use it when

  • Counting connected components or islands
  • Detecting cycles
  • Exploring every path, with backtracking

Avoid it when

  • You need the shortest path in an unweighted graph - use BFS
  • Very deep graphs with recursion in Python - use an explicit stack

Complexity cheatsheet

OperationTimeSpace
DFS on a graphO(V + E)O(V)
DFS on an r × c gridO(r × c)O(r × c)
Recursion depth, worst case-O(V)

Often confused with: BFS - it explores by distance; DFS explores by depth.

03

How to recognize it

Clues in interview prompts that point straight to this pattern.

islandsconnectedpath existscycleall paths
  • On grids, mark cells visited by overwriting them if you may change the input
  • Cycle detection in directed graphs needs three states: unvisited, in progress, done
04

Mistakes & edge cases

Catch common off-by-one bugs and corner cases before submitting.

Common mistakes

  • Counting diagonal neighbours when the prompt says 4-directional
  • Recursing before marking the cell visited - infinite recursion
  • Hitting the recursion limit on large grids

Edge cases to test

  • An empty grid
  • All water or all land
  • A single row or a single column
Interview tip: Mention the recursion limit and offer an iterative stack version for large grids.
05

Knowledge check

Quick check to lock in the intuition.

Question 1 of 3

Why mark a cell as visited before exploring its neighbours?

06

Practice

Apply what you just watched on real interview problems.

Generate Depth-First Search problem in AI DSA Practice →
  • BeginnerIsland PerimeterLeetCode 463 ↗ (opens in a new tab)
  • IntermediateNumber of IslandsLeetCode 200 ↗ (opens in a new tab)
  • AdvancedLongest Increasing Path in a MatrixLeetCode 329 ↗ (opens in a new tab)
Breadth-First SearchTopological Sorting