Topic 07 of 14
Graph Patterns
4 patterns and 20 practice problems, each with a recall tip, a diagram, the theory and a Python template.
01
Graph - BFS (Shortest Path Unweighted)
5 practice problems
Theory
- BFS explores nodes level by level — first time you reach a node is the shortest path.
- Use a queue and a visited set. Process all neighbors before going deeper.
- Multi-source BFS: add all sources to the queue initially for "distance from nearest source".
- Time: O(V + E), Space: O(V).
Code template
python
from collections import deque
def bfs_shortest_path(graph, start, end):
queue = deque([(start, 0)])
visited = {start}
while queue:
node, dist = queue.popleft()
if node == end:
return dist
for nei in graph[node]:
if nei not in visited:
visited.add(nei)
queue.append((nei, dist + 1))
return -1Practice problems · 5
Medium#200
Hard#127
Medium#994
Medium#1091
Medium#752
02
Graph - DFS (Connected Components / Cycle Detection)
5 practice problems
Theory
- DFS explores as deep as possible before backtracking.
- For connected components: run DFS from every unvisited node, count starts.
- Cycle detection (directed): track recursion stack. If you revisit a node in the current path — cycle.
- Cycle detection (undirected): if you visit an already-visited node that is not the parent — cycle.
Code template
python
def count_components(n, edges):
graph = {i: [] for i in range(n)}
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
visited = set()
count = 0
def dfs(node):
visited.add(node)
for nei in graph[node]:
if nei not in visited:
dfs(nei)
for i in range(n):
if i not in visited:
dfs(i)
count += 1
return countPractice problems · 5
Medium#207
Medium#133
Medium#417
Medium#130
03
Graph - Topological Sort
5 practice problems
Theory
- Only works on DAGs (Directed Acyclic Graphs).
- Kahn's algorithm (BFS): process nodes with in-degree 0, reduce neighbors' in-degree.
- DFS variant: add node to result in postorder (after all descendants), then reverse.
- If result length < number of nodes — cycle exists.
Code template
python
from collections import deque
def topo_sort(num_nodes, edges):
graph = {i: [] for i in range(num_nodes)}
in_degree = {i: 0 for i in range(num_nodes)}
for u, v in edges:
graph[u].append(v)
in_degree[v] += 1
queue = deque([n for n in in_degree if in_degree[n] == 0])
order = []
while queue:
node = queue.popleft()
order.append(node)
for nei in graph[node]:
in_degree[nei] -= 1
if in_degree[nei] == 0:
queue.append(nei)
return order if len(order) == num_nodes else []Practice problems · 5
Medium#207
Medium#210
Hard#269
Medium#310
Medium#444
04
Graph - Union Find (Disjoint Set)
5 practice problems
Theory
- Track connected components with parent[] and rank[] arrays.
- find(x): follow parent pointers to root, with path compression.
- union(x, y): merge two sets by connecting roots. Use union by rank to keep trees flat.
- Near O(1) amortized per operation with both optimizations.
Code template
python
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
self.components = n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px == py: return False
if self.rank[px] < self.rank[py]:
px, py = py, px
self.parent[py] = px
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
self.components -= 1
return TruePractice problems · 5
Medium#547
Medium#684
Medium#721
Medium#128
Medium#261
Spotted a mistake on this page?
Wrong formula, broken animation or confusing wording. Tell us and we will fix it.