Graph Representation
Adjacency Lists in Python
Learn how to represent graphs using dictionaries of lists and sets in Python: the most flexible and widely-used approach in coding interviews and real-world applications.
What is a Graph?
A graph is a data structure made of two components: nodes (also called vertices) connected by edges. Graphs model relationships: friendships on social media, roads between cities, dependencies between tasks.
Key Vocabulary
Why Representation Matters
A graph drawn on paper is intuitive, but computers need a structured format to store and traverse it. The way you represent a graph determines how fast you can:
The Adjacency List: Core Idea
An adjacency list maps each vertex to a collection of its neighbors. In Python, we use a dictionary where each key is a node and each value is a list or set of neighbors.
Lists vs Sets as Values
The neighbors can be stored as a list or a set. Each choice has trade-offs:
| dict of lists | dict of sets | |
|---|---|---|
| Edge lookup | \( O(n) \) : scan list | \( O(1) \) average |
| Add edge | \( O(1) \) : append | \( O(1) \) : add |
| Remove edge | \( O(n) \) : find + remove | \( O(1) \) : discard |
| Duplicate edges | Possible (must guard) | Automatically prevented |
| Preserves order | Yes | No |
Building an Undirected Graph
For an undirected graph, every edge is bidirectional. When you add edge (u, v), add v to u's list and u to v's list.
Building a Directed Graph
For a directed graph, edge (u, v) means u → v only. We add v to u's list but not the reverse.
Cleaner Code with defaultdict
Python's collections.defaultdict auto-creates missing keys, eliminating the need for explicit if key not in checks.
Step-by-Step Approach
dict of list or set. Use defaultdict for convenience.(u, v), append/add v to graph[u]. If undirected, also add u to graph[v].graph[node] returns all neighbors. Iterate to run BFS/DFS.Example 1: Simple Undirected Graph
Example 2: Directed Graph
Example 3: Larger Graph with Sets
Common Operations
Common Mistakes
v to graph[u] but forgetting to add u to graph[v] for undirected graphs.graph[5] should still exist as [].Representation Summary
| Adjacency List | Adjacency Matrix | Edge List | |
|---|---|---|---|
| Space | \( O(V + E) \) | \( O(V^2) \) | \( O(E) \) |
| Edge check | \( O(\text{deg}) \) or \( O(1) \) | \( O(1) \) | \( O(E) \) |
| All neighbors | \( O(\text{deg}) \) | \( O(V) \) | \( O(E) \) |
| Add edge | \( O(1) \) | \( O(1) \) | \( O(1) \) |
| Best for | Sparse graphs | Dense graphs | Simple storage |
Question 1 of 5
Given an undirected graph with edge (A, B), which adjacency list is correct?
Question 2 of 5
What is the main advantage of using defaultdict(set) over defaultdict(list) for an adjacency list?
Question 3 of 5
Given this directed graph code, what does graph[2] return?
Code:
from collections import defaultdict
graph = defaultdict(list)
for u, v in [(1,2), (2,3), (3,1)]:
graph[u].append(v)
graph[u].append(v) is called. Node 2 appears as u only in edge (2, 3), so graph[2] is [3].Question 4 of 5
What is the space complexity of an adjacency list for a graph with \( V \) vertices and \( E \) edges?
Question 5 of 5
You have an undirected graph stored as a dict of lists. How do you find the degree of node "X"?
graph["X"] is a list of all neighbors, len(graph["X"]) gives the degree directly.