hub

Graphs
Curriculum

Master graph algorithms through traversal patterns, connectivity analysis, and systematic exploration of relationships.

What This Category Is Really About

hubRelationships & Connections

Nodes (vertices) connected by edges. Models networks, dependencies, relationships. Most general data structure—trees are special graphs.

exploreTraversal & Search

DFS and BFS are fundamental. Explore all reachable nodes systematically. Handle cycles, multiple components, directed vs undirected.

device_hubConnectivity & Components

Which nodes are reachable from which? Connected components, strongly connected components, bridges, articulation points.

routePaths & Shortest Paths

Finding paths between nodes. Shortest path algorithms: BFS (unweighted), Dijkstra (weighted), Bellman-Ford (negative weights).

Mental Model & Invariants

Graphs are networks of relationships explored through systematic traversal.

"Mark nodes as visited to avoid cycles. Track state (distance, parent, color) to extract information during traversal."

The Core Invariant
Every node is either unvisited, being processed, or fully processed. Visited set prevents infinite loops. State tracking extracts graph properties.

Break this, and you get infinite loops or missed nodes.

check_circle

Visited Invariant

Mark nodes as visited before processing. Never revisit. Prevents cycles and ensures termination.

straighten

Path Invariant

Track parent pointers during traversal. Reconstruct path by backtracking from target to source.

social_distance

Distance Invariant

BFS discovers nodes in order of distance. First visit to a node is shortest path (unweighted).

explore

Choose Your Traversal

DFS for paths, cycles, topological sort. BFS for shortest paths, level-by-level. Both explore all reachable nodes.

When to Think "Graphs"

sensorsStrong Signals

draw

Network of connections (social, computer, roads)

draw

Dependencies between entities

draw

Shortest path between points

draw

Reachability questions

draw

Cycle detection needed

draw

Connected components

ruleProblem Signals

hub

Many-to-many relationships

hub

Traversal order matters

hub

Need to explore all possibilities

hub

Optimization over network structure

Core Patterns You Must Master

account_tree

DFS (Depth-First Search)

Explore as far as possible before backtracking. Stack-based (recursive or explicit).

// Invariant
Visit node, mark visited, recurse on unvisited neighbors.
CyclesPathsTopological
layers

BFS (Breadth-First Search)

Explore level by level. Queue-based. Shortest path in unweighted graphs.

// Invariant
Process nodes in order of distance from source.
Shortest pathLevel-orderQueue
device_hub

Connected Components

Find groups of connected nodes. Run DFS/BFS from each unvisited node.

// Invariant
Each component explored completely before moving to next.
Union-FindDFSIslands
sync

Cycle Detection

Detect cycles in directed/undirected graphs. DFS with color states.

// Invariant
Back edge indicates cycle. Track visiting vs visited.
DFSColorsBack edge
sort

Topological Sort

Linear ordering of DAG nodes. Dependencies before dependents.

// Invariant
Node added to result after all descendants processed.
DFSDAGPost-order
route

Shortest Path

BFS (unweighted), Dijkstra (weighted), Bellman-Ford (negative weights).

// Invariant
Relaxation: update distance if shorter path found.
BFSDijkstraPriority queue

How to Learn This Category

1

Master DFS and BFS First

Implement both from scratch. Understand when to use each. Practice on simple graphs. Trace execution by hand.

2

Learn Graph Representations

Adjacency list vs adjacency matrix. Understand tradeoffs. Practice converting between representations.

3

Handle Visited State Correctly

Mark nodes visited before processing. Understand difference between visiting and visited. Prevent infinite loops.

4

Practice Cycle Detection

Detect cycles in directed and undirected graphs. Understand back edges, cross edges, forward edges.

5

Master Topological Sort

Understand DAG properties. Implement using DFS post-order. Recognize dependency problems.

6

Learn Shortest Path Algorithms

BFS for unweighted. Dijkstra for weighted positive. Bellman-Ford for negative weights. Understand when each applies.

Canonical Problem List

Common Mistakes

error_outline

Not Marking Nodes as Visited

Failure Mode

Infinite loops in cyclic graphs. Revisiting same nodes repeatedly.

Mastery Fix

Mark node as visited immediately when discovered, before processing neighbors.

error_outline

Confusing Directed vs Undirected

Failure Mode

Wrong edge interpretation. Bidirectional when should be unidirectional.

Mastery Fix

Clarify graph type upfront. In undirected, add edges both ways. In directed, respect edge direction.

error_outline

Wrong Traversal Choice

Failure Mode

Using DFS when BFS needed for shortest path. Or vice versa.

Mastery Fix

BFS for shortest path (unweighted), level-order. DFS for paths, cycles, topological sort.

error_outline

Not Handling Disconnected Components

Failure Mode

Only exploring from one starting node. Missing entire components.

Mastery Fix

Loop through all nodes. Start traversal from each unvisited node.

error_outline

Incorrect Cycle Detection

Failure Mode

Marking visited too early/late. Not distinguishing visiting vs visited.

Mastery Fix

Use three states: unvisited, visiting (in current path), visited (fully processed).

Interview Guidance

Interview Protocol

What they test

  • DFS vs BFS selection
  • Visited state management
  • Handling disconnected components
  • Graph representation choice

Strategy

Draw the graph. Clarify directed vs undirected. Ask about disconnected components. Choose traversal based on problem requirements. Explain visited tracking.

The Verbal Template

Graph Type

"Is this directed or undirected? Weighted or unweighted? Can there be cycles?"

Representation

"I'll use adjacency list for sparse graphs. Allows efficient neighbor iteration."

Traversal

"I'll use [DFS/BFS] because [reason: shortest path / cycle detection / etc]."

Visited

"I'll track visited nodes with a set/array. Mark visited when discovered to prevent loops."

When You've Mastered It

done_all

Implement DFS and BFS instantly

done_all

Choose correct traversal for problem

done_all

Handle visited state without bugs

done_all

Detect cycles reliably

done_all

Implement topological sort

done_all

Recognize graph problems immediately

What This Unlocks Next

route

Advanced Shortest Path

Dijkstra, Bellman-Ford, Floyd-Warshall. A* search. Handling negative weights and cycles.

account_tree

Minimum Spanning Trees

Kruskal's and Prim's algorithms. Union-Find data structure. Network design problems.

water_drop

Network Flow

Max flow, min cut. Ford-Fulkerson, Edmonds-Karp. Bipartite matching.

hub

Advanced Graph Algorithms

Strongly connected components (Tarjan, Kosaraju). Bridges and articulation points. Eulerian paths.