A graph is a set of vertices (nodes) joined by edges (links). Graphs model anything built from relationships: roads between cities, links between web pages, friendships, package dependencies, network cables, moves in a puzzle. Before you can run any graph algorithm you need two things: the vocabulary to describe the graph in front of you, and a representation in memory, because that choice decides how fast every algorithm on top of it will run.
Think of it like
A city road map
Intersections are vertices and streets are edges. A one-way street is a directed edge, a two-way street is undirected, and the street's length or travel time is its weight. You can store the city as a giant distance table (every intersection against every other), as a per-intersection list of streets leaving it, or as a plain list of streets. Same city, three representations, very different costs to answer "which streets leave this corner?"
The vocabulary
Formally a graph is a pair G = (V, E). By convention V (or n) is the number of vertices and E (or m) is the number of edges. Complexities in this module are written in terms of both, because a graph with a million vertices can have a few million edges or a trillion.
- Adjacent / neighbor
- Vertices
uandvare adjacent if an edge connects them. The edge is incident to both. - Degree
- Number of edges touching a vertex. In a directed graph it splits into in-degree (edges arriving) and out-degree (edges leaving).
- Path
- A sequence of vertices where each consecutive pair is joined by an edge. A simple path never repeats a vertex. Its length is the number of edges (or the sum of weights).
- Cycle
- A path that starts and ends at the same vertex with at least one edge (at least three in a simple undirected graph). A graph with no cycles is acyclic.
- Connected
- An undirected graph is connected if every vertex can reach every other. Otherwise it splits into connected components.
- Strongly / weakly connected
- A directed graph is strongly connected if every vertex can reach every other following edge directions; weakly connected if it is connected once directions are ignored.
- Weighted
- Each edge carries a number (distance, cost, capacity, probability). Unweighted graphs behave as if every weight is 1.
- DAG
- A directed acyclic graph: directed edges and no directed cycles. Dependency graphs, build graphs and schedules are DAGs.
- Tree / forest
- A connected acyclic undirected graph is a tree; it always has exactly
V - 1edges. A forest is a collection of trees. - Self-loop / multi-edge
- An edge from a vertex to itself, or several parallel edges between the same pair. A simple graph has neither.
- Sparse / dense
- Sparse graphs have
E = O(V)edges (roads, social networks). Dense graphs haveE = Θ(V²)edges (complete graphs, distance tables). - Bipartite
- Vertices split into two sides so that every edge crosses between the sides (jobs and workers, students and courses).
Directed vs undirected
Undirected
- Edge
{u, v}can be traversed both ways - Friendships, roads, cables, grid cells
- Stored as two directed entries:
u → vandv → u - Connectivity is about components
Directed
- Edge
(u, v)goes fromutovonly - Follows on social media, web links, prerequisites
- Stored once, in
u's list - Connectivity is about reachability and strongly connected components
The handshake lemma
Every undirected edge has two endpoints, so it adds exactly 2 to the total degree. Summing the degrees therefore counts every edge twice. In a directed graph each edge adds 1 to some out-degree and 1 to some in-degree, so both sums equal E.
How many edges can there be?
| Graph | Edge count | Example |
|---|---|---|
Tree on n vertices | exactly n - 1 | File system hierarchy, a spanning tree |
| Simple undirected | at most n(n - 1)/2 | Complete graph K₅ has 10 edges |
| Simple directed | at most n(n - 1) | Every pair linked both ways |
| Sparse (typical real network) | O(n) | Road network: ~3 roads per intersection |
| Dense | Θ(n²) | Flight prices between every pair of airports |
E to V² decides which representation and which algorithms are practical.Representing a graph in memory
Here is one small undirected graph, with edges 0-1, 0-2, 1-2, 1-3, 3-4, written in each of the three standard representations. The visualization above lets you switch between them on your own graphs.
# Undirected graph with edges 0-1, 0-2, 1-2, 1-3, 3-4
edge_list = [(0, 1), (0, 2), (1, 2), (1, 3), (3, 4)]
adjacency_list = [
[1, 2], # neighbors of 0
[0, 2, 3], # neighbors of 1
[0, 1], # neighbors of 2
[1, 4], # neighbors of 3
[3], # neighbors of 4
]
adjacency_matrix = [
# 0 1 2 3 4
[0, 1, 1, 0, 0], # 0
[1, 0, 1, 1, 0], # 1
[1, 1, 0, 0, 0], # 2
[0, 1, 0, 0, 1], # 3
[0, 0, 0, 1, 0], # 4
]
# Weighted versions store the weight next to the neighbor:
# adjacency_list[u] = [(v, w), ...]
# adjacency_matrix[u][v] = w (and inf, or None, for "no edge")Adjacency matrix
V × Vgrid;M[u][v] = 1(or the weight) if the edge existsO(1)edge lookup, trivially simpleO(V²)memory even if the graph is nearly empty- Listing a vertex's neighbors costs
O(V) - Symmetric for undirected graphs
Adjacency list
- One list (array, vector) of neighbors per vertex
O(V + E)memory: proportional to the actual graph- Neighbors of
uinO(deg(u)), ideal for BFS and DFS - Edge lookup is
O(deg(u)), orO(1)average with hash sets - The default choice for almost every problem
Edge list
- A flat array of
(u, v)or(u, v, w)tuples O(E)memory, the format most inputs arrive in- Easy to sort by weight (Kruskal's MST)
- Natural for Bellman-Ford, which scans every edge each round
- Terrible for "who are the neighbors of
u?"
| Operation | Adjacency matrix | Adjacency list | Edge list |
|---|---|---|---|
| Memory | O(V²) | O(V + E) | O(E) |
Is there an edge (u, v)? | O(1) | O(deg(u)) | O(E) |
Iterate neighbors of u | O(V) | O(deg(u)) | O(E) |
| Iterate every edge | O(V²) | O(V + E) | O(E) |
| Add an edge | O(1) | O(1) | O(1) |
| Remove an edge | O(1) | O(deg(u)) | O(E) |
| Add a vertex | O(V²) | O(1) | O(1) |
The memory gap is not academic. Consider a social network with one million users and an average of 10 friends each, so E = 5 million undirected edges.
Adjacency matrix
125 GB
10¹² cells at 1 bit each
Adjacency list
~40 MB
10⁷ neighbor ids × 4 bytes, plus headers
Edge list
~40 MB
5 × 10⁶ edges × 2 ids × 4 bytes
Density
0.001%
5 × 10⁶ of ~5 × 10¹¹ possible edges
Large static graphs in production (web graphs, road networks, graph databases' read paths) often use compressed sparse row (CSR) format: one array holds every neighbor list back to back, and an offsets array of size V + 1 says where each vertex's slice starts. It is an adjacency list with no per-vertex allocation, so it is compact and cache-friendly.
Implicit graphs
Many graph problems never hand you a graph. Instead you are given a grid, a puzzle or a set of rules, and the graph exists only implicitly: vertices are states and edges are legal moves. You generate a vertex's neighbors on the fly when an algorithm asks for them, and you never build the whole thing in memory.
| Problem | Vertex | Edge |
|---|---|---|
| Maze or island grid | A cell (r, c) | Step to an adjacent open cell (4 or 8 directions) |
| Open the Lock | A 4-digit string like "0000" | Turn one wheel up or down by one |
| Word Ladder | A dictionary word | Change exactly one letter |
| 8-puzzle | A board configuration | Slide a tile into the blank |
| Knight's tour | A board square | One L-shaped knight jump |
DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1)) # down, up, right, left
# For 8-directional movement add (1, 1), (1, -1), (-1, 1), (-1, -1)
def neighbors(grid: list[str], r: int, c: int):
rows, cols = len(grid), len(grid[0])
for dr, dc in DIRECTIONS:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#":
yield nr, nc
# A cell can also be flattened to a single integer id: id = r * cols + cBuilding a graph from input
Interview and contest problems usually give n plus an edge list such as [[0, 1], [1, 2]], sometimes with a weight as a third element. Converting that to an adjacency list is the first few lines of almost every graph solution, and most graph bugs live in those lines.
- 1
Decide directed or undirected
Read the statement carefully. "Course
arequiresb" is directed, and the edge goesb → a. Roads and friendships are undirected. - 2
Normalize vertex ids
Convert 1-indexed input to 0-indexed, or allocate
n + 1lists. Map string labels (airport codes, emails) to integers with a hash map. - 3
Allocate a list for every vertex
Create
nempty lists up front so isolated vertices still exist. Building from edges alone silently drops them. - 4
Add each edge
Append
vtoadj[u]; for undirected graphs also appendutoadj[v]. Store(v, w)pairs for weighted graphs. - 5
Watch for duplicates and self-loops
If the input may repeat an edge, either tolerate it (BFS and DFS do) or deduplicate with sets.
Which algorithm for which problem?
Once you can say what the vertices and edges are, and whether the graph is directed and weighted, the algorithm usually picks itself. This map is a preview of the rest of the module.
| Question | Algorithm | Time |
|---|---|---|
Can u reach v? How many components? | Breadth-First Search, Depth-First Search or Union-Find (Disjoint Set) | O(V + E) |
Fewest edges from s to every vertex | Breadth-First Search | O(V + E) |
| Shortest path, weights 0 or 1 | 0-1 BFS | O(V + E) |
| Shortest path, non-negative weights | Dijkstra's Algorithm | O((V + E) log V) |
| Shortest path with negative weights | Bellman-Ford (Bellman-Ford & Floyd-Warshall) | O(V · E) |
| Shortest paths between all pairs | Floyd-Warshall (Bellman-Ford & Floyd-Warshall) | O(V³) |
| Point-to-point route with a good distance estimate | A* Pathfinding | O((V + E) log V) worst case |
| Order tasks with dependencies | Topological Sort | O(V + E) |
| Does a cycle exist? | Depth-First Search (colors) or Union-Find (Disjoint Set) | O(V + E) |
| Connect everything at minimum total cost | Minimum Spanning Trees | O(E log V) |
| Groups in a directed graph, critical links | SCCs, Bridges & Articulation Points | O(V + E) |
| Is the graph two-colorable? | BFS or DFS 2-coloring | O(V + E) |
Complexity
| Operation | Adjacency matrix | Adjacency list | Edge list |
|---|---|---|---|
| Space | O(V²) | O(V + E) | O(E) |
Edge check (u, v) | O(1) | O(deg(u)) | O(E) |
Neighbors of u | O(V) | O(deg(u)) | O(E) |
| Visit every edge | O(V²) | O(V + E) | O(E) |
| Add edge | O(1) | O(1) | O(1) |
| Remove edge | O(1) | O(deg(u)) | O(E) |
deg(u) is the degree of u. For undirected adjacency lists, removing an edge also updates v's list. Hash-set neighbor containers make edge checks O(1) on average.
Implementation
The opening lines of most graph solutions, plus in-degrees (used by topological sort) and a handshake-lemma sanity check.
def build_adjacency_list(n: int, edges: list[tuple[int, int]], directed: bool = False) -> list[list[int]]:
adj: list[list[int]] = [[] for _ in range(n)] # one list per vertex, even isolated ones
for u, v in edges:
adj[u].append(v)
if not directed:
adj[v].append(u) # undirected: store both directions
return adj
def in_degrees(adj: list[list[int]]) -> list[int]:
indeg = [0] * len(adj)
for neighbors in adj:
for v in neighbors:
indeg[v] += 1
return indeg
adj = build_adjacency_list(5, [(0, 1), (0, 2), (1, 2), (1, 3), (3, 4)])
# adj == [[1, 2], [0, 2, 3], [0, 1], [1, 4], [3]]
assert sum(len(nbrs) for nbrs in adj) == 2 * 5 # handshake lemmaKey takeaways
- A graph is
G = (V, E); always ask whether it is directed, weighted, cyclic and how dense it is before picking an algorithm. - The handshake lemma (
Σ deg = 2E) is why adjacency-list traversals costO(V + E)and why odd-degree vertices come in pairs. - Adjacency lists are the default:
O(V + E)memory and fast neighbor iteration. Matrices suit small or dense graphs; edge lists suit edge-centric algorithms. - Many problems hide an implicit graph (grid cells, puzzle states, words); generate neighbors on demand instead of materializing edges.
- Allocate a list for every vertex up front, normalize ids, and get the edge direction right: most graph bugs live in the input-parsing lines.
Common pitfalls
- Adding only one direction for an undirected edge, so traversals miss half the graph.
- Reversing the direction of dependency edges ("
arequiresb" isb → a). - Building the vertex set from edges alone and silently dropping isolated vertices.
- Using an
O(V²)adjacency matrix for a sparse graph with 10⁵ or more vertices and running out of memory. - Creating a Python matrix with
[[0] * n] * n, which makes every row the same list object.
Interview tips
- Clarify directed vs undirected, weighted vs unweighted, possible cycles, self-loops, duplicate edges, and the sizes of
VandE. - When the input is a grid or a set of rules, say "this is an implicit graph where each state is a vertex" before writing any code.
- Quote complexities in terms of both
VandE(O(V + E), notO(n)), and mention whenEcan be as large asV².
Real-world applications
- Road networks and navigation (intersections and road segments).
- Social networks: friendships (undirected) and follows (directed).
- The web graph: pages and hyperlinks, the input to PageRank and crawlers.
- Package managers and build tools: dependency DAGs.
- Computer networks, power grids and pipelines: routing and resilience analysis.
- Recommendation systems and knowledge graphs: entities and relationships.
Practice problems
Test yourself
An undirected graph has 7 edges. What is the sum of the degrees of all its vertices?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.