Graph Fundamentals
A graph is a collection of vertices (nodes) connected by edges, used to model pairwise relationships between objects. Graphs power social networks, GPS navigation, dependency resolution, network routing, and a huge share of interview problems. BFS and DFS are the two fundamental traversal algorithms; from them flow cycle detection, shortest paths, topological sort, and connected-component analysis.
What is a Graph?
A graph G = (V, E) consists of a set of vertices V and a set of edges E that connect pairs of vertices. Unlike trees, graphs can have cycles, disconnected components, and edges with weights or directions. This flexibility makes graphs the go-to structure whenever you need to model relationships — friendships, road maps, task dependencies, web links, circuit connections, or state machines.
Graphs are stored in two main representations:
Map<V, List<V>>
Each vertex stores a list of its neighbours. Space-efficient for sparse graphs (E ≪ V²) and supports fast iteration over neighbours.
- Space: O(V + E)
- Add edge: O(1)
- Check edge: O(degree)
- Best for most interview problems
boolean[V][V]
A V×V matrix where matrix[u][v] = true means an edge from u to v. O(1) edge lookup but wastes space for sparse graphs.
- Space: O(V²)
- Add edge: O(1)
- Check edge: O(1)
- Best for dense graphs or Floyd-Warshall
| Type | Edges | Cycles | Example |
|---|---|---|---|
| Undirected | Bidirectional | Possible | Social network friendships |
| Directed (Digraph) | One-way | Possible | Web page links, Twitter follows |
| DAG | Directed | None | Build systems, task scheduling |
| Weighted | Have costs | Possible | Road networks, airline routes |
| Bipartite | Two groups | Even cycles only | Job matching, student-course |
Core Operations
Diagrams & Structure
Java Quick Reference
Adjacency-list graph with BFS, DFS, and topological sort — the three operations that cover 90% of interview graph problems.
Time & Space Complexity
| Operation | Time | Space |
|---|---|---|
| Add Edge (adj list) | O(1) | O(1) |
| Check Edge (adj list) | O(degree) | O(1) |
| Check Edge (adj matrix) | O(1) | O(1) |
| BFS / DFS | O(V + E) | O(V) |
| Topological Sort | O(V + E) | O(V) |
| Dijkstra (min-heap) | O((V + E) log V) | O(V) |
| Bellman-Ford | O(V · E) | O(V) |
| Floyd-Warshall | O(V³) | O(V²) |
| Union-Find (amortised) | O(α(N)) ≈ O(1) | O(V) |
Adjacency list: O(V + E) — each vertex has a list entry, each edge appears once (directed) or twice (undirected). Adjacency matrix: O(V²) regardless of edges. For sparse graphs (E ≪ V²), adjacency lists can be orders of magnitude more space-efficient. BFS/DFS additionally use O(V) for the visited set and queue/stack.
When to Use Graph
Use This When
- Shortest path / minimum steps — BFS for unweighted, Dijkstra for weighted, Bellman-Ford for negative weights.
- Dependency ordering — topological sort for course schedules, build systems, task pipelines.
- Connected components — BFS/DFS or Union-Find to count islands, friend circles, or network clusters.
- Cycle detection — DFS with state tracking for directed graphs; Union-Find for undirected.
- Grid problems — treat each cell as a vertex with 4 edges — Number of Islands, Shortest Path in Grid, etc.
Avoid When
- Hierarchical data only — if there are no cycles and one root, a tree is simpler and more efficient.
- Sequential access — if you just need ordered traversal, arrays or linked lists are better.
- Key-value lookup — HashMap gives O(1) access without graph overhead.
| Problem Type | Algorithm | Time | Key Constraint |
|---|---|---|---|
| Shortest path (unweighted) | BFS | O(V + E) | All edges weight 1 |
| Shortest path (weighted, no neg) | Dijkstra | O((V+E) log V) | Non-negative weights |
| Shortest path (negative weights) | Bellman-Ford | O(V · E) | No negative cycles |
| All-pairs shortest path | Floyd-Warshall | O(V³) | Small V (≤ 400) |
| Dependency ordering | Topological Sort | O(V + E) | Must be a DAG |
| Minimum spanning tree | Kruskal / Prim | O(E log E) | Connected, undirected |
| Connected components | Union-Find / BFS | O(V + E) | Dynamic: prefer Union-Find |
LeetCode Problems
Graph problems in interviews test your ability to model a situation as vertices and edges, then pick the right traversal. The three core patterns are: BFS for shortest distance, DFS for exhaustive exploration, and topological sort for dependency ordering. If the problem mentions “connected”, “reachable”, “shortest”, “schedule”, or “prerequisites”, think graph.
- MediumNumber of Islands — BFS/DFS flood-fill on a 2D grid — the classic “count connected components” problem.
- MediumClone Graph — BFS/DFS with a HashMap to map original nodes to clones — tests deep copy of graph structure.
- MediumCourse Schedule — Detect cycles in a directed graph using topological sort or DFS with 3-color marking.
- MediumCourse Schedule II — Return a valid topological ordering; Kahn’s algorithm is the cleanest approach.
- MediumPacific Atlantic Water Flow — Multi-source BFS/DFS from ocean borders; find cells reachable from both oceans.
- MediumNetwork Delay Time — Dijkstra’s algorithm on a weighted directed graph — find the time for all nodes to receive a signal.
- MediumRedundant Connection — Union-Find to find the edge that creates a cycle in an undirected graph.
- HardWord Ladder — BFS on an implicit graph where words differing by one letter are connected — shortest transformation sequence.
- HardAlien Dictionary — Build a directed graph from sorted alien words, then topological sort to find character order.
- HardCheapest Flights Within K Stops — Modified Dijkstra / BFS with level constraint — tests graph + DP thinking.