Graph Representation
Adjacency Lists in Java
Learn how to model graphs using Map<Integer, List<Integer>>: the most flexible and practical representation for coding interviews, competitive programming, and real-world applications.
What Is a Graph?
A graph is a data structure consisting of a set of vertices (nodes) and a set of edges (connections). Formally: \( G = (V, E) \), where \( V \) is the vertex set and \( E \) is the edge set.
Key Vocabulary
Why Adjacency Lists?
Graphs can be stored in many ways, but adjacency lists offer the best trade-off of memory efficiency and traversal speed for most real-world and competitive programming problems.
The Data Structure
In Java, we represent an adjacency list as:
Adjacency List vs Adjacency Matrix
| Adjacency List | Adjacency Matrix | |
|---|---|---|
| Space | \( O(V + E) \) | \( O(V^2) \) |
| Check edge \( (u,v) \) | \( O(\text{degree}(u)) \) | \( O(1) \) |
| List neighbors | \( O(\text{degree}(u)) \) | \( O(V) \) |
| Add edge | \( O(1) \) | \( O(1) \) |
| Best for | Sparse graphs | Dense graphs |
How to Build It: Step by Step
Example 1: Undirected Graph
Example 2: Directed Graph
Example 3: Building from an Edge List
Many problems give you \( V \) vertices and an array of edges. Here is a reusable pattern to build the adjacency list:
The computeIfAbsent Shortcut
Instead of pre-initializing every vertex, you can use Java's computeIfAbsent method, which creates the list on demand:
Traversing Neighbors
Once built, the adjacency list makes it simple to visit all neighbors of a given vertex. This is the foundation of BFS and DFS:
Directed vs Undirected Edge Insertion
Degree of a Vertex
The degree of a vertex is the number of edges connected to it. With an adjacency list, the degree is simply the size of the neighbor list:
Common Mistakes
Summary Cheat Sheet
| Operation | Code | Time |
|---|---|---|
| Create graph | new HashMap<>() | \( O(1) \) |
| Add vertex | graph.put(v, new ArrayList<>()) | \( O(1) \) |
| Add edge | graph.get(u).add(v) | \( O(1) \) |
| Get neighbors | graph.get(u) | \( O(1) \) |
| Get degree | graph.get(u).size() | \( O(1) \) |
| Check edge | graph.get(u).contains(v) | \( O(\text{deg}) \) |
| Total space | — | \( O(V + E) \) |
Question 1 of 5
What is the space complexity of an adjacency list for a graph with \( V \) vertices and \( E \) edges?
Question 2 of 5
For an undirected graph with edge \( (3, 7) \), which lines of code correctly add this edge to the adjacency list?
Question 3 of 5
Given an undirected graph with 4 vertices and edges \( (0,1), (0,2), (1,3) \), what does graph.get(0) return?
Question 4 of 5
What does computeIfAbsent do in the context of building a graph?
Question 5 of 5
In a directed graph represented as an adjacency list, the out-degree of vertex \( u \) is: