dsapatterns©
01Home02Patterns03Questions04
Cheatsheet
05Notes06Dashboard

© 2026 DSAPatterns

dsapatterns©
Cheatsheet
dsapatterns©
01Home02Patterns03Questions04
Cheatsheet
05Notes06Dashboard

© 2026 DSAPatterns

dsapatterns©
Cheatsheet
dsapatterns©
01Home02Patterns03Questions04
Cheatsheet
05Notes06Dashboard

© 2026 DSAPatterns

dsapatterns©
Cheatsheet
Cheatsheet›Graphs
CORE PATTERNVery High Frequency

Graphs

A graph is a set of nodes (vertices) connected by edges. Unlike trees, graphs can have cycles, disconnected components, and edges with weights or directions. Key algorithms — DFS, BFS, Union-Find, Dijkstra, and topological sort — cover virtually every graph problem encountered in interviews.

TimeO(V + E)
SpaceO(V + E)
DifficultyMedium to Hard

Key Insight

Model the problem as a graph, then choose DFS, BFS, or shortest path.

Flip ⟲
GraphsBFS
ABCDEF
Queue:
A
start BFS at A
Graphs Cheatsheet
FLIP SIDEGraphs
Tap to flip back ⟲

RECOGNITION SIGNALS (WHEN TO USE THIS PATTERN)

✓Islands, regions, or connected components in a grid or graph
✓Shortest path between two nodes (weighted or unweighted)
✓Detect a cycle in a directed or undirected graph
✓Topological ordering of tasks with dependencies
✓Union-Find / dynamic connectivity queries
✓Minimum spanning tree or network cost
1

Types of Problems (Subpatterns)

Each subpattern solves a specific type of problem. Click on a card to view its template.

✓ SELECTED

Graph DFS

Explore as deep as possible from each unvisited node — mark visited to avoid revisiting.

  • Number of Islands
  • Max Area of Island
  • Clone Graph
5 problems

Graph BFS — Shortest Path

BFS explores layer by layer — the first time you reach a node is via the shortest path.

  • Shortest Path in Binary Matrix
  • Rotting Oranges
  • Word Ladder
5 problems

Union-Find (DSU)

Track connected components dynamically — union in O(α) amortized with path compression + rank.

  • Number of Connected Components in an Undirected Graph
  • Redundant Connection
  • Graph Valid Tree
5 problems

Topological Sort

Order nodes so all directed edges point forward — use Kahn's BFS or DFS post-order.

  • Course Schedule
  • Course Schedule II
  • Alien Dictionary
5 problems

Dijkstra's Algorithm

Greedy shortest path for non-negative edge weights — min-heap drives expansion in order of distance.

  • Network Delay Time
  • Path With Minimum Effort
  • Cheapest Flights Within K Stops
5 problems

Cycle Detection

Undirected: parent tracking. Directed: three-colour DFS (white/grey/black).

  • Course Schedule (detect cycle in directed graph)
  • Graph Valid Tree (undirected, no cycle)
  • Redundant Connection
5 problems

Minimum Spanning Tree

Connect all nodes with minimum total edge weight — Kruskal (DSU) or Prim (heap).

  • Minimum Cost to Connect All Points
  • Min Cost to Connect Ropes
  • Optimize Water Distribution in a Village
5 problems
2

Template / Approach

Template for: Graph DFS

Approach

1

Build Adjacency List

Represent the graph as unordered_map<int, vector<int>> or a 2D vector. For grids, neighbours are the 4 (or 8) adjacent cells.

2

Track Visited

Keep a visited array or set. Mark a node visited before recursing into its neighbours — prevents infinite loops in cyclic graphs.

3

DFS Each Component

Iterate every node; if unvisited, call dfs(node). This ensures all disconnected components are explored.

Template

</>Common Template
💡Graph DFS skeleton for adjacency-list graphs. For grid DFS, replace the adjacency list with 4-directional neighbour generation and use (row, col) as the visited key.
🔑
Key Idea:Mark visited before recursing (not after) to handle cycles. For grids, sinking visited cells (setting to '0') avoids a separate visited array. For disconnected graphs, always loop over all nodes and call DFS on each unvisited one.
1// Graph DFS — adjacency list, O(V + E)
2vector<vector<int>> adj; // adj[u] = list of neighbours of u
3vector<bool> visited;
4
5void dfs(int node)
6{
7    visited[node] = true;
8
9    for (int neighbour : adj[node])
10    {
11        if (!visited[neighbour])
12        {
13            dfs(neighbour);
14        }
15    }
16}
17
18// Call for every unvisited node to handle disconnected components
19int countComponents(int n)
20{
21    adj.assign(n, {});
22    visited.assign(n, false);
23    int components = 0;
24
25    for (int i = 0; i < n; i++)
26    {
27        if (!visited[i])
28        {
29            dfs(i);
30            components++;
31        }
32    }
33
34    return components;
35}
Medium

Number of Islands

LeetCode #200

Medium

Max Area of Island

LeetCode #695

Medium

Clone Graph

LeetCode #133

Medium

Pacific Atlantic Water Flow

LeetCode #417

Medium

Surrounded Regions

LeetCode #130

Medium

Shortest Path in Binary Matrix

LeetCode #1091

Medium

Rotting Oranges

LeetCode #994

Hard

Word Ladder

LeetCode #127

Medium

01 Matrix

LeetCode #542

Medium

Jump Game III

LeetCode #1306

Medium

Number of Connected Components in an Undirected Graph

LeetCode #323

Medium

Redundant Connection

LeetCode #684

Medium

Graph Valid Tree

LeetCode #261

Medium

Accounts Merge

LeetCode #721

Medium

Course Schedule

LeetCode #207

Medium

Course Schedule II

LeetCode #210

Hard

Alien Dictionary

LeetCode #269

Medium

Minimum Height Trees

LeetCode #310

Medium

Network Delay Time

LeetCode #743

Medium

Path With Minimum Effort

LeetCode #1631

Medium

Cheapest Flights Within K Stops

LeetCode #787

Medium

Path With Maximum Probability

LeetCode #1514

Medium

Find Eventual Safe States

LeetCode #802

Medium

Detect Cycle in Directed Graph

LeetCode #207

Medium

Minimum Cost to Connect All Points

LeetCode #1584

Hard

Optimize Water Distribution in a Village

LeetCode #1168

Hard

Find Critical and Pseudo-Critical Edges in MST

LeetCode #1489

dsapatterns

SEE THE PATTERNS. MASTER THE ALGORITHMS. ACE THE INTERVIEWS.

Visual DSA pattern library built to turn complex algorithms into clear, intuitive structures.

LEARN

  • Patterns
  • Questions
  • Notes
  • Cheatsheet

BUILD

  • Notes

© 2026 DSAPATTERNS. ALL RIGHTS RESERVED.

DESIGNED & BUILT WITH CARE

FAQsPrivacy PolicyCookies Policy