Introduction to graphs
easy 18 minA graph is a set of vertices joined by edges, directed or undirected, weighted or not.
See it run
Build a graph one vertex and edge at a time, store it as an adjacency list and a matrix, then walk it with DFS and BFS using a visited set.
Operations
Add vertex and edge
Start from an empty graph, add three vertices, then connect them. An undirected edge is stored in both neighbour lists.
Step 1 of 7
An empty graph
Counts
V = 0 · E = 0
A graph is a set of vertices (the dots) and edges (the lines between them). We store it as a dictionary: each vertex maps to the list of its neighbours. Right now there is nothing in it.
Step 1: An empty graph
class Graph: def __init__(self): self.adj = {} # vertex -> list of neighbours def add_vertex(self, v): if v not in self.adj: self.adj[v] = [] # new vertex, no edges yet def add_edge(self, u, v, directed=False): self.add_vertex(u) self.add_vertex(v) self.adj[u].append(v) if not directed: self.adj[v].append(u) # undirected: store both ways- Time
- O(1) each
- Space
- O(1) each
- Matrix: add vertex
- O(V²) to resize
- Matrix: add edge
- O(1)
For an undirected graph always write both directions. Forgetting the reverse append is the most common bug in graph code: the graph quietly becomes directed.
In the real world
The same introduction to graphs doing real jobs. Pick one and step through it.
People are vertices and friendships are undirected edges. Degree is a friend count, and mutual friends are shared neighbours.
Step 1 of 4
Five people, six friendships
Each person is a vertex and each friendship an edge. Friendship goes both ways (if Ana is Ben's friend, Ben is Ana's), so the graph is undirected, like Facebook.
Step 1: Five people, six friendships
friends = { "Ana": ["Ben", "Dee"], "Ben": ["Ana", "Cy", "Dee", "Eli"], "Cy": ["Ben", "Eli"], "Dee": ["Ana", "Ben"], "Eli": ["Ben", "Cy"],}print(len(friends["Ben"])) # 4 friendsprint(set(friends["Ana"]) & set(friends["Eli"])) # {'Ben'}Common mistakes
The bugs interviewers watch for, with the fix beside each.
Adding only one direction in an undirected graph
criticalIf A-B is stored only in adj[A], a traversal from B never finds A. The graph silently becomes directed and answers come out wrong.
Wrongfor u, v in edges: adj[u].append(v)Rightfor u, v in edges: adj[u].append(v) adj[v].append(u) # undirected: both endsTraversing a graph without a visited set
criticalTrees have no cycles, so tree DFS needs no memory. Graphs do: without a visited set, DFS recurses forever and BFS re-queues vertices without end.
Wrongdef dfs(u): for v in adj[u]: dfs(v) # loops forever on a cycleRightdef dfs(u, visited): visited.add(u) for v in adj[u]: if v not in visited: dfs(v, visited)Starting only from vertex 0 on a disconnected graph
majorOne traversal reaches only one connected component. Vertices in other components are never visited. Loop over every vertex and start a new traversal from each unvisited one.
Wrongvisited = set()dfs(0, visited) # misses other componentsRightvisited, parts = set(), 0for v in range(n): if v not in visited: parts += 1 dfs(v, visited)Forgetting isolated vertices
majorBuilding the graph only from the edge list leaves vertices with no edges out of the dictionary, so they are missed in counts and loops, or raise KeyError. Create a list for every vertex first.
Wrongadj = {}for u, v in edges: adj.setdefault(u, []).append(v) adj.setdefault(v, []).append(u)# vertex 4 with no edges is missingRightadj = {v: [] for v in range(n)}for u, v in edges: adj[u].append(v) adj[v].append(u)Using a matrix for a huge sparse graph
majorA matrix always costs V² cells. For 100,000 vertices that is 10 billion cells, far beyond memory, even if there are only 200,000 edges. An adjacency list needs V + 2E.
Wrongmatrix = [[0] * n for _ in range(n)] # n = 100_000Rightadj = [[] for _ in range(n)] # O(V + E)Sharing one inner list with [[0] * n] * n
minorMultiplying a list of lists copies the reference, so every row is the same object and setting one cell sets the whole column. Build each row separately.
Wrongmatrix = [[0] * n] * nmatrix[0][1] = 1 # every row now has a 1 in column 1Rightmatrix = [[0] * n for _ in range(n)]matrix[0][1] = 1
Interview tips
How to explain it
- A graph is a set of vertices and a set of edges between pairs of them: G = (V, E).
- Edges can be directed or undirected, weighted or unweighted. Trees, grids and DAGs are all special graphs.
- Store it as an adjacency list (O(V + E) space) unless the graph is small and dense, when a matrix (O(V²)) gives O(1) edge checks.
- Walk it with DFS or BFS plus a visited set: O(V + E) time.
Clarify before coding
- Directed or undirected? Weighted? Can there be self-loops or repeated edges?
- Is the graph connected, or might there be several components?
- How are vertices named: 0 to n − 1, or strings? That decides list of lists versus dictionary.
- How large are V and E? That decides list versus matrix.
The template
- adj = [[] for _ in range(n)]; for u, v in edges: adj[u].append(v); adj[v].append(u)
- visited = set(); for each unvisited start: traverse and mark.
- DFS for reachability, components and cycles; BFS for fewest edges.
- Grids are implicit graphs: each cell is a vertex, its four neighbours are edges.
Facts to have ready
- Handshake lemma: the degrees add up to 2E, so the number of odd-degree vertices is even.
- Max edges: V(V − 1)/2 undirected, V(V − 1) directed, without self-loops.
- A tree on V vertices has exactly V − 1 edges and no cycles.
- Matrix: O(1) edge check, O(V) neighbours. List: O(deg) edge check, O(deg) neighbours.