01 / 21

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.

Java Data Structures

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.

0 1 2 3 edge vertex (node)

Key Vocabulary

Vertex
A single node in the graph, often labeled with an integer.
Edge
A connection between two vertices: \( (u, v) \).
Neighbor
Vertex \( v \) is a neighbor of \( u \) if edge \( (u,v) \) exists.
Directed
Edges have a direction: \( u \to v \) does not imply \( v \to u \).
Undirected
Edges are bidirectional: \( (u, v) = (v, u) \).

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.

1
Space: \( O(V + E) \): stores only edges that exist, not empty connections.
2
Fast neighbor access: iterating over a vertex's neighbors is \( O(\text{degree}) \).
3
Flexible: works naturally for sparse and dense graphs, directed and undirected.

The Data Structure

In Java, we represent an adjacency list as:

Map<Integer, List<Integer>> graph = new HashMap<>();
Key (Vertex) 0 1 2 3 [1, 3] [0, 2] [1, 3] [0, 2] Value (Neighbor List)

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

1
Create the map: initialize a HashMap<Integer, List<Integer>>.
2
Add each vertex: put an empty ArrayList for every node.
3
Insert edges: for each edge \( (u, v) \), add \( v \) to the list of \( u \).
4
If undirected: also add \( u \) to the list of \( v \) (both directions).

Example 1: Undirected Graph

0 1 2
// Edges: (0,1), (0,2), (1,2) Map<Integer, List<Integer>> graph = new HashMap<>(); for (int i = 0; i < 3; i++) graph.put(i, new ArrayList<>()); // Add edges (both directions for undirected) graph.get(0).add(1); graph.get(1).add(0); graph.get(0).add(2); graph.get(2).add(0); graph.get(1).add(2); graph.get(2).add(1);

Example 2: Directed Graph

0 1 2 3 0 → 1 1 → 2 0 → 3 3 → 2
// Directed edges: 0→1, 0→3, 1→2, 3→2 Map<Integer, List<Integer>> graph = new HashMap<>(); for (int i = 0; i < 4; i++) graph.put(i, new ArrayList<>()); graph.get(0).add(1); graph.get(0).add(3); graph.get(1).add(2); graph.get(3).add(2);

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:

int n = 5; // number of vertices int[][] edges = {{0,1},{0,4},{1,2},{1,3},{3,4}}; Map<Integer, List<Integer>> graph = new HashMap<>(); // Initialize all vertices for (int i = 0; i < n; i++) graph.put(i, new ArrayList<>()); // Populate edges (undirected) for (int[] e : edges) { graph.get(e[0]).add(e[1]); graph.get(e[1]).add(e[0]); }

The computeIfAbsent Shortcut

Instead of pre-initializing every vertex, you can use Java's computeIfAbsent method, which creates the list on demand:

Map<Integer, List<Integer>> graph = new HashMap<>(); for (int[] e : edges) { graph.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]); graph.computeIfAbsent(e[1], k -> new ArrayList<>()).add(e[0]); }
Advantage
No need for a separate initialization loop: shorter, cleaner code.
Caution
Isolated vertices (no edges) won't appear as keys unless you add them manually.

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:

// Print all neighbors of vertex 0 for (int neighbor : graph.get(0)) { System.out.println("0 -> " + neighbor); } // Or iterate all vertices and their neighbors for (int node : graph.keySet()) { for (int nbr : graph.get(node)) { System.out.println(node + " -> " + nbr); } }

Directed vs Undirected Edge Insertion

Directed u v graph.get(u).add(v); (one direction only) Undirected u v graph.get(u).add(v); graph.get(v).add(u); (both directions)

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:

int degree = graph.get(u).size();
Undirected
\( \text{degree}(u) \) = graph.get(u).size()
Directed: Out-degree
\( \text{outDegree}(u) \) = graph.get(u).size()
Directed: In-degree
Requires scanning all lists (or maintaining a separate count).

Common Mistakes

✕ Forgetting Both Directions
For undirected graphs, forgetting to add the edge in both directions causes missing neighbors during traversal.
✕ Missing Initialization
Calling graph.get(v).add(...) on an uninitialized vertex throws a NullPointerException.
✕ Duplicate Edges
Adding the same edge twice without checking creates parallel edges, breaking algorithms like shortest path.

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: