Graphs Cheat Sheet
Quick reference for coding interviews. Bookmark this page!
What is Graphs?
Model relationships and connections between entities.
Trigger Words
When you see these in a problem, think Graphs:
Template Code
def numIslands(grid: List[List[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
count = 0
def dfs(r, c):
if r < 0 or r >= rows or c < 0 or c >= cols:
return
if grid[r][c] != '1':
return
grid[r][c] = '0' # Mark visited
dfs(r + 1, c)
dfs(r - 1, c)
dfs(r, c + 1)
dfs(r, c - 1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1':
count += 1
dfs(r, c)
return count
Complexity
| Typical Time | O(m × n) |
|---|---|
| Typical Space | O(m × n) |
Common Variations
- Basic Graphs
- Graphs with constraints
- Optimized Graphs
Practice Problems
See all Graphs problems →Practice Graphs
Learn to recognize patterns instantly with interactive MCQs.
Download LeetEye Free