Graphs [00LL]
- September 13, 2026
In this next unit, we will learn about (or review) graphs and several fundamental graph algorithms.
Graph definitions and terminology [00LM]
- September 13, 2026
The material in this section is introduced via POGIL activity; see the activity for illustrations and examples.
Definition (Simple) graph [00LN]
- September 13, 2026
A (simple) graph G = (V, E) is a set of vertices V (singular vertex) together with a set E of edges, where each edge consists of a set of two vertices.
Remark Graphs and graph drawings [00LO]
- September 13, 2026
We often draw graphs with a dot for each vertex, and edges represented by (straight or curved) lines drawn between vertices. Note that the same graph can have many different drawings; the important thing about a graph is which vertices are connected by edges, not the specific way it is drawn.
Definition Adjacent vertices [00LP]
- September 13, 2026
Vertices are adjacent (or neighbors) if they share an edge.
Definition Degree [00LQ]
- September 13, 2026
The degree of a vertex is the number of other vertices which are adjacent to it. The degree of a vertex v is often abbreviated \deg (v).
Definition Leaf [00LR]
- September 13, 2026
A leaf is a vertex with degree 1.
Definition Path [00LS]
- September 13, 2026
A path is a sequence of one or more vertices such that each consecutive pair of vertices is adjacent.
Definition Connected [00LT]
- September 13, 2026
Two vertices are connected if there is a path with the two vertices as endpoints. A connected graph is one where every pair of vertices are connected. A connected component is a maximal subset of connected vertices.
Definition Cycle [00LU]
- September 13, 2026
A cycle is a path which starts and ends at the same vertex and does not repeat any edges. A cyclic graph is a graph containing at least one cycle. An acyclic graph is a graph with no cycles.
Definition Tree [00LV]
- September 13, 2026
Some proofs about trees [00M0]
- September 14, 2026
The proofs in this section are also covered in a POGIL activity.
We pause here to prove a fundamental theorem about trees, partly as an example of the types of proofs we often do with graphs, and partly because trees show up all over the place and this theorem is of practical importance when designing algorithms.
Theorem Trees [00M1]
- September 14, 2026
Connected, acyclic graphs have n-1 edges [00M2]
- September 14, 2026
This is a proof of one part of the previous theorem, namely, that (1) and (2) together imply (3).
Proof.
- September 14, 2026
Let P(n) denote the statement “Any graph G with n vertices which is connected and acyclic must have n-1 edges.” We wish to show that P(n) holds for all n \geq 1.
The proof is by induction on n.
- The base case is when n = 1. In this case, G is just a single vertex, so it is indeed connected, acyclic, and has 0 edges.
For the induction step, suppose P(k) holds for some k \geq 1. That is, suppose that any graph with k vertices which is connected and acyclic must have k-1 edges. Then we wish to show P(k+1), that is, any graph with k+1 vertices which is connected and acyclic must have k edges.
So, let G be a graph with k+1 vertices which is connected and acyclic. We claim that G must have some vertex which is a leaf, that is, a vertex of degree 1, which we can show as follows:
- G cannot have any vertices of degree 0, because it is connected (and has at least two vertices).
- It also cannot be the case that every vertex of G has degree \geq 2. If they did, then we could find a cycle by starting at any vertex and walking along edges randomly until encountering a repeated vertex; we would never get stuck because every vertex has degree \geq 2, that is, if we come in along one edge there must always be a different edge along which we can leave. However, this is impossible because we assumed G is acyclic.
Hence, G must have some vertex which is a leaf. If we delete this vertex along with the edge adjacent to it, it results in a graph G' with only k vertices; we note that G' is still connected (because G was connected and we deleted a leaf) and also acyclic (because deleting something from an acyclic graph cannot create a cycle). Hence we may apply the induction hypothesis to conclude that G' has k-1 edges. Adding the deleted vertex and edge back to G' shows that G has k edges, which is what we wanted to show.
Acyclic graphs with n-1 edges are connected [00M3]
- September 14, 2026
This is a proof of another part of the previous theorem, namely, that (2) and (3) together imply (1). It uses a counting argument: we will show what we wish to show by counting things in multiple ways.
Proof.
- September 14, 2026
Let c denote the number of connected components of G. We want to show that c = 1.
Number the components of G from 1 \dots c, and say that component i has n_i vertices. Then \sum _{i=1}^c n_i = n, because adding up the number of vertices in each component gives the total number of vertices. Each connected component is by definition a connected graph; each component must also be acyclic since we assumed that G is acyclic. Hence we may apply Connected, acyclic graphs have n-1 edges to conclude that component i has n_i - 1 edges. Adding these up, the total number of edges in G is |E| = \sum _{i=1}^c (n_i - 1) = \left (\sum _{i=1}^c n_i \right ) - \left (\sum _{i=1}^c 1 \right ) = n - c. But we already assumed the number of edges in G is n-1, and hence c = 1 as desired.
[G5] Connected graphs with n-1 edges must be acyclic (2 pts) [00M4]
- September 14, 2026
Prove that for all n \geq 1, if G is a simple connected graph with n vertices and n-1 edges, then G has no cycles. (This is the third part of the proof from class, characterizing trees as having any two out of three properties.)
You may freely assume Connected, acyclic graphs have n-1 edges and Acyclic graphs with n-1 edges are connected if they are helpful; I also recommend studying their proofs as examples.
Hint.
- September 14, 2026
Use induction on n. By counting vertex degrees, show that any connected graph with k+1 vertices and k edges must have at least one leaf.
Hint.
- September 14, 2026
Use the [G4] Handshake lemma (1 pt).
Depth-first search (DFS) [00M6]
- September 17, 2026
DFS introduction and intuition [00M7]
- September 17, 2026
The first graph algorithm we will learn about can answer simple questions of connectivity: given a graph G and particular vertices s and t, are they connected by a path? If so, what is one such path?
The basic idea is to explore as far as you can in a certain direction before backtracking and continuing to explore further unexplored paths, and so on, just like you might explore a physical maze. The problem is loops: we need some way to mark vertices that we have already visited, so we know if we have been somewhere before and don’t get stuck exploring a loop forever. Just like we might mark where we have been by placing rocks on the ground in a physical maze, we can mark previously visited vertices with "digital rocks" so we don't get caught in a loop.
Algorithm DFS (version 1) [00M8]
- September 17, 2026
Notice that we implement DFS via recursion. Perhaps you have also seen a version that uses an explicit stack data structure. By using recursion, we essentially get our programming language's runtime system to keep track of the stack for us. Maintaining a stack ourselves can get annoying and messy, especially if we want to create any extra local variables during the DFS. However, a word of caution: using recursion in this way does not work so well in certain languages (where by "certain languages" I mean "Python"), especially if the graph is large.
To see if vertices s and t are connected, we can just run \mathsf {DFS}(G, s) and see if t is marked visited. Optionally, we can also stop early as soon as we find t during the DFS (left as an exercise).
Correctness of DFS [00MB]
- September 18, 2026
How do we know that DFS does what we want? First of all, we need to argue that it won't go off into an inifinite loop or infinite recursion.
Theorem DFS terminates [00MC]
- September 18, 2026
For any finite graph G and any unvisited vertex u, \mathsf {DFS}(G,u):
- terminates in finite time, and
- decreases the number of unvisited vertices.
Proof.
- September 18, 2026
- If u is the only unvisited vertex, then the \mathsf {if} statement inside the loop will never be true, so \mathsf {DFS} will never call itself recursively and will terminate after iterating through all the neighbors of u (since G is finite, u can only have a finite number of neighbors). It also marks u visited, thus decreasing the number of unvisited vertices.
- Otherwise, the first action of \mathsf {DFS}(G,u) is to mark u visited, thus decreasing the number of unvisited vertices by one. Each recursive call to an unvisited neighbor \mathsf {DFS}(G,v) will be with fewer unvisited vertices, and therefore by the induction hypothesis will terminate and reduce the number of unvisited vertices further.
Remark [00ME]
- September 18, 2026
We also note that \mathsf {DFS}(G,v) terminates even if we call it on a visited vertex v, since it will proceed to call itself recursively on only the unvisited neighbors of v, so the above theorem applies to each of the recursive calls.
There are many things we could prove about DFS—indeed, DFS has a lot of nice properties that can be used for all sorts of purposes which we sadly don't have time to talk about—but the most basic one is that DFS discovers which vertices are connected and which are not.
DFS solves connectivity [00MD]
- September 18, 2026
Assuming all vertices start out unvisited, \mathsf {DFS}(G,s) ends up visiting t if and only if s and t are connected.
Proof.
- September 18, 2026
- By definition, \mathsf {DFS} only explores along edges, i.e. paths. If s and t are not connected, there is no way that \mathsf {DFS} starting from s will be able to reach t.
If s and t are connected, by definition there must be some path from s to t. Since we already know \mathsf {DFS} always terminates, we can do induction on the number of recursive calls needed for \mathsf {DFS} to complete.
Suppose the next vertex on the path from s to t is v, so there is an edge between s and v. Then either the call to \mathsf {DFS}(G,s) will make a recursive call to \mathsf {DFS}(G,v) (if v is unvisited), or else if v is already visited it means that a call to \mathsf {DFS}(G,v) already happened. In either case, our induction hypothesis tells us that the recursive call \mathsf {DFS}(G,v) will end up visiting t; hence so will the original call \mathsf {DFS}(G,s).
Algorithm DFS (version 2, with parent tree) [00M9]
- September 17, 2026
What if we want to find an explicit path from s to t? As it stands, we can't: we need more information. In particular, we need to know how we got to each vertex. We can add a parent dictionary which stores the parent of each visited vertex. Every time we visit a vertex, we record its parent, i.e. the neighbor we "came from".
Note that the resulting \mathit {parent} dictionary records a tree, representing the paths we took while exploring the graph. However, instead of the each node recording its children, each node simply records its parent. So we can easily move up the tree, but not down.
That's OK though—moving up is all we need! In order to find a path from s to t (in reverse order) we can look up \mathit {parent}[t], \mathit {parent}[\mathit {parent}[t]], and so on.
Time complexity of DFS [00MA]
- September 18, 2026
What is the time complexity of this algorithm? First of all, it matters how we represent the visited vertices. We can use a dictionary (with vertices as keys and booleans as values), or an array of booleans (if the vertices are numbered 0 \dots n-1), or a set of visited vertices. Assuming some kind of array or hash table-based structure, the operations of marking a vertex as visited or checking to see if a vertex is visited should take \Theta (1).
Now, this algorithm is recursive, and we will spend some time later in the semester talking about how to analyze recursive algorithms in general, but thankfully we can do something much simpler in this case:
- We call DFS at most once for each vertex.
- We iterate over the edges adjacent to each vertex (assume it takes O(\deg (u)) to iterate over the vertices adjacent to u). This means we look at each edge twice (once from each end).
Thus the entire algorithm takes something like O(V+E), where V is the number of vertices and E is the number of edges (formally we should write |V| and |E| but we just abbreviate them as V and E). Note that we don’t use “n”: there is nothing magical about the letter n, and in this case we prefer to use the letters V and E to denote the number of vertices and number of edges, respectively.
Note also that we can’t necessarily simplify O(V+E): E might be much less than V, or much greater. We could argue that this particular version is actually O(E) (assuming it takes \Theta (1) to initialize the data structure used to track visited vertices), but we often use a variant version that loops over all vertices and calls DFS from each unvisited vertex.
Other DFS applications [00MJ]
- September 21, 2026
There are many other applications of DFS—far too many to cover in this course! I will just list a few and let you look them up if you are interested.
- DFS can be used to find articulation points (aka cut vertices) and bridges, i.e. vertices and edges whose removal would disconnect a graph.
- DFS can be used to topologically sort a directed graph. We will learn a different algorithm for this later.
- DFS can be used to find the strongly connected components of a directed graph; this is known as Kosaraju's algorithm.
- Given a rooted tree, we can run DFS with a gobal "time" counter and label each vertex with the time we started processing it and the time we finished processing it. Then we can answer ancestry queries in \Theta (1)—to check whether vertex a is an ancestor of vertex b in the tree, just check whether b's start and end times lie within a's start and end times.
Breadth-first search (BFS) [00MK]
- September 21, 2026
Motivation for BFS [00ML]
- September 21, 2026
DFS can find a path between given vertices, if one exists; but it is not guaranteed to find the shortest path. For example, consider the graph consisting of four vertices connected into a cycle. The shortest path from any vertex to an adjacent vertex is clearly of length 1; but if DFS happens to search in the other direction first, it will find the path of length 3 instead.
So, if we want to find not just any path between vertices in a graph, but the shortest path, what can we do? This is a natural question in many contexts, where the shortest path corresponds to a cheapest/quickest/simplest solution.
BFS specification [00MM]
- September 21, 2026
The shortest path problem can be solved by the breadth-first search (BFS) algorithm. The basic idea behind BFS is to start at a vertex s and explore outward in all directions, adding vertices one “layer” at a time. That is, layer zero is just L_0 = \{s\}; layer 1 is all neighbors of s; layer 2 is all the neighbors of layer 1 vertices which were not already in layers 0 or 1; and so on.
Formally, we can define \begin {align*}L_0 &= \{s\} \\ L_{k+1} &= \left ( \bigcup _{v \in L_k} N(v) \right ) - \left ( \bigcup _{i \leq k} L_i \right )\end {align*} where N(v) denotes the set of all v's neighbors.
We claim that the layers defined in this way have the following properties. In particular, the first theorem below tells us that BFS (if we can implement it somehow) will solve the shortest path problem: to find the shortest path from s to t, just run BFS starting from s, and see what layer t shows up in. In fact, we don't need a particular target vertex in mind; just running BFS starting from s will tell us about the shortest path from s to every vertex. The second lemma is something we will use layer.
Theorem BFS layers correspond to shortest paths [00MN]
- September 21, 2026
For every k \geq 0 and every vertex v, the shortest path from s to v has length k if and only if v \in L_k.
Proof.
- September 21, 2026
Intuitively, this says that if v shows up in layer k, then that means the shortest path from s to v has length k, and vice versa. If v is in layer k, then there is definitely a path of length k from s to v, since we can get from each layer to the next via a single edge; and if there were a shorter path, v would have shown up in an earlier layer.
Formally, the proof is by induction on k.
- When k = 0, we must show that for any v, the shortest path from s to v has length 0 if and only if v \in L_0. This is true because s is the only vertex in L_0, and if a path from s to v has length 0 then v = s.
- Now let k \geq 1 and suppose as our induction hypothesis that for any j < k, the shortest path from s to any u has length j if and only if u \in L_{j}. Now consider some vertex v. We must show both directions of the if and only if.
Subproof. BFS layers correspond to shortest paths ›
- September 21, 2026
Suppose the shortest path from s to v has length k, and suppose the next-to-last vertex in the shortest path (that is, the vertex right before v) is u. The part of the path from s to u must also be a shortest path of length k-1 (if there were a shorter path from s to u, then we could just add on the edge from u to v to create a path from s to v of length < k), so by the induction hypothesis u \in L_{k-1}. Then since v is a neighbor of u, v \in L_k (v can't be in any earlier layers since then the induction hypothesis would imply there is a path to v shorter than k).Subproof. BFS layers correspond to shortest paths ›
- September 21, 2026
Now suppose v \in L_k. By definition, it must have a neighbor u \in L_{k-1}. By the induction hypothesis, the shortest path to u must have length k-1; adding back the edge between u and v yields a path to v of length k. This must be a shortest path, since if there were a shorter one, the induction hypothesis again tells us that v would have been in an earlier layer and hence not in L_k.
Lemma Neighbors are in adjacent layers [00MO]
- September 21, 2026
If u and v are neighbors, then the layers of u and v differ by at most one.
Proof.
- September 21, 2026
Algorithm BFS implementation [00MP]
- September 21, 2026
The parent and layer maps are optional, and can be used to find actual shortest paths and the shortest distance from s to each vertex, respectively.
BFS running time [00MQ]
- September 21, 2026
Since the implementation of BFS shown above has two nested loops, it must take \Theta (n^2) time, right? Not necessarily! (Also, we don't even have anything here named n.) However, by a similar argument as we used to analyze DFS, this algorithm examines each vertex at most once and each edge at most twice, performing various constant-time operations along the way (in particular we can implement a queue so that enqueue and dequeue both take constant time). Hence, the entire algorithm is O(V+E).
This is about the best we could possibly hope for—any interesting graph algorithm has to at least look at the entire graph, and simply reading every vertex and every edge takes \Theta (V+E) time.
Practical notes on implementing BFS [00MR]
- September 21, 2026
If you implement BFS in a real programming language (you should try it!), be sure you use a good data structure for your queue! For example, Python lists make an extremely poor list substitute: it is possible to append or remove items from the end of a list in constant time, but, say, removing an element from the beginning of a list takes linear time! Using a list instead of a real queue would therefore make BFS take O(V^2 + E) instead of O(V+E), which could make a huge difference. For example, processing a graph with one million vertices (as long as it does not have too many edges) would take a fraction of a second using an O(V+E) algorithm, but an O(V^2+E) algorithm could take on the order of (10^6)^2 / 10^8 = 10^4 seconds, or almost three hours. A graph with 10 million vertices would still take less than a second with an efficient BFS, but an O(V^2) algorithm could take more than a week.
- In Java, you can use the
ArrayDequeclass, which implements theQueueinterface. - In Python, you can use the
dequeclass from thecollectionslibrary. - In C++, you can use a
std::queue.
Bipartite graphs [00MX]
- September 22, 2026
Bipartite graphs: intuition and motivation [00MZ]
- September 22, 2026
Suppose we are trying to schedule TA hours. We have a set of available time slots and a set of TAs, and each TA is available during certain time slots. We can model this situation with a graph: make a vertex for each TA, a vertex for each time slot, and connect each TA to all the time slots for which they are available.
Notice that in this example, we have two kinds of vertices, and the edges only go from one kind of vertex to the other kind. This kind of graph is called bipartite, and they show up a lot—any time we want to model some kind of relationship between two sets.
Not only can we use bipartite graphs to model lots of things, but many problems which are difficult for graphs in general become easy in the case of bipartite graphs. For example, the problem of scheduling TAs is a matching or assignment problem, which is difficult for graphs in general, but can be solved for bipartite graphs using a maximum flow (which we will learn about later in the semester).
Definition Bipartite graph [00MY]
- September 22, 2026
An undirected graph G = (V,E) is bipartite if V can be partitioned into two sets L and R such that every edge has one endpoint in L and one in R.
Definition Graph coloring [00N0]
- September 23, 2026
As a generalization of bipartite graphs, we can also think about graph coloring. The idea is to give every vertex a "color" in such a way that no edge has the same color on both ends.
Definition k-colorable [00N1]
- September 23, 2026
An undirected graph is k-colorable if it is possible to assign each vertex one of k colors, in such a way that no two vertices of the same color are adjacent.
Remark Bipartite = 2-colorable [00N2]
- September 23, 2026
Being bipartite is the same as being 2-colorable—instead of thinking in terms of putting the vertices on one side or the other, we can think in terms of coloring them, say, red and blue. But we can also talk about graphs being 3-colorable, 4-colorable, and so on. Deciding whether a graph is 2-colorable—that is, bipartite—can be done quite efficiently, as we will see in a moment. Surprisingly, it turns out that deciding whether a graph is k-colorable for k \geq 3 is quite difficult!
Theorem Bipartite = no odd cycles [00N3]
- September 23, 2026
An undirected graph G is bipartite iff it has no odd-length cycles.
Proof.
- September 23, 2026
Subproof. Bipartite = no odd cycles ›
- September 23, 2026
Subproof. Bipartite = no odd cycles ›
- September 23, 2026
(\Longleftarrow ) Suppose G = (V,E) has no odd-length cycles; we must show G is bipartite. Pick an arbitrary vertex s and run a BFS, generating layers L_0, L_1, L_2, …. Then define \begin {gather*} L = L_0 \cup L_2 \cup L_4 \cup \dots \\ R = L_1 \cup L_3 \cup L_5 \cup \dots \end {gather*}
We now claim that L and R are a vertex partition showing that G is bipartite, that is, every edge \{x,y\} \in E has one endpoint in L and one in R. By the single-layer-difference property of BFS, there can’t be any edges between different layers within L or R. The only possibility we have to worry about is an edge between two vertices in the same layer; we must show this can't happen.
So, suppose \{x,y\} \in E and x,y \in L_j; we will derive a contradiction. Let z be the least common ancestor of x and y in the BFS tree, and suppose z has height h above x and y. Then z \to x \to y \to z forms a cycle of length 2h + 1, which is odd—but we assumed G has no odd cycles. Therefore such an edge \{x,y\} within a single layer cannot exist, and G is indeed bipartite.
Remark BFS is a test for bipartiteness [00N4]
- September 23, 2026
The above proof does much more than just establish the truth of the theorem. It actually describes a practical algorithmic test for bipartiteness. Run a BFS starting from any vertex; then G is bipartite iff there is no edge between two vertices in the same layer. If there is a cross-edge within a layer, then we have found an odd cycle; otherwise, we have found a 2-coloring of the graph.
That is, this algorithm tells us not only whether a graph is bipartite, but gives us concrete (and easily checkable) evidence to support the conclusion: either an odd cycle, showing the graph is not bipartite, or a specific partition of the vertices showing that it is.
Directed graphs and DAGs [00N5]
- September 24, 2026
Definition Directed graph [00N6]
- September 24, 2026
A directed graph is just like an undirected graph, except that the edges are ordered pairs of vertices, E \subseteq V \times V. This means that each edge has a particular direction: an edge goes from one vertex to another vertex instead of just connecting two vertices.
We typically draw directed graphs by putting arrowheads on the edges to indicate which direction they go.
Remark Generalizing from undirected to directed graphs [00N7]
- September 24, 2026
Lots of things generalize naturally to directed graphs: instead of paths we have directed paths, which follow edges "in the right direction", as if the directions are one-way signs we have to obey. Instead of degree we have indegree (the number of edges pointing into a vertex) and outdegree (the number of edges pointing out). DFS and BFS extend naturally to directed graphs as well. If we only follow edges in the direction they are supposed to go—i.e. if at each vertex we only look at outgoing neighbors—then neither algorithm needs any changes, and they find directed paths.
In some ways, directed graphs are actually more "fundamental" than undirected graphs. The various ways we have to represent graphs (adjacency matrices and adjacency lists) naturally represent directed graphs, and if we want an undirected edge we essentially have to put in two directed edges, one in each direction.
DAGs and topological ordering [00N8]
- September 24, 2026
Definition DAG [00N9]
- September 24, 2026
A directed acyclic graph (DAG) is a directed graph with no directed cycles.
Remark DAG examples [00NA]
- September 24, 2026
In general, we tend to use DAGs to represent dependency relationships. For example:
- The graph of courses at Hendrix where there is a directed edge X \to Y when class Y has class X as a prerequisite
- The graph of modules in a software project where an edge X \to Y means that module Y imports module X
- A graph of tasks where an edge X \to Y means that task X must be completed before task Y
Definition Topological ordering [00NB]
- September 24, 2026
A topological ordering (topological order, topological sort, topsort) of a directed graph is an ordering of nodes v_1, \dots , v_n such that for every (v_i, v_j) \in E, we have i < j.
Remark Topological ordering means "edges all point to the right" [00NC]
- September 24, 2026
In other words, a topological ordering is a way to put the vertices of a graph in order so that the edges only point to the right. This corresponds to a consistent order in which classes can be taken, tasks can be done, etc. so the prerequisites are always met.
Theorem DAG \leftrightarrow topsort [00ND]
- September 24, 2026
A directed graph G has a topological ordering iff G is a DAG.
Proof.
- September 24, 2026
Subproof. DAG \leftrightarrow topsort ›
- September 24, 2026
Subproof. DAG \leftrightarrow topsort ›
- September 24, 2026
Lemma. DAG \to indegree 0 [00NE]
- September 24, 2026
Any DAG has a vertex with indegree 0.
Proof.
- September 24, 2026
Remark. [00NF]
- September 24, 2026
Note that this proof implicitly depends on the fact that the graph is finite (we only consider finite graphs in this class). Does the lemma still hold for infinite DAGs?
Now we prove that if G is a DAG, it has a topological ordering. Proof by induction on n / recursive algorithm.
- Base case: if n = 1 there is only one vertex and no edges, so there is a trivial topological ordering.
- If n > 1, find a vertex v with indegree 0 by the previous lemma/algorithm. Note that G - \{v\} (the graph formed by deleting vertex v and any adjacent edges) is also a DAG, since deleting things cannot create any cycles. Then by the induction hypothesis, G - \{v\} has a topological ordering. Adding v at the beginning then makes a valid topological ordering for G since v has no incoming edges.
Time complexity of naive topsort [00NG]
- September 24, 2026
The algorithm described in the above proof, for computing a topological ordering of a DAG, takes \Theta (V^2) time: searching for an indegree-0 vertex takes \Theta (V) time in the worst case (if we have to walk backwards through most of the graph), and we have to do it once for each vertex. But we can do better when the graph is sparse. The idea is to maintain some extra information that allows us to quickly find a vertex with indegree 0 on each iteration without searching.
Theorem Efficient topsort [00NH]
- September 24, 2026
A topological sorting algorithm can be implemented in \Theta (V+E) time.
Proof.
- September 24, 2026
We assume an adjacency list representation for the input graph.
We need to be able to quickly find the next remaining vertex with indegree 0 on each iteration (we don’t want to re-run a linear search every time), and also quickly delete a vertex (updating the indegrees of other vertices appropriately).
The idea is to maintain two data structures:
- An array/dictionary \mathit {in} where \mathit {in}[v] = the indegree of v. We can initialize this dictionary in \Theta (V + E) time: just iterate through every vertex u and increment \mathit {in}[v] for each outgoing edge u \to v.
- A queue/stack/whatever Z of vertices with indegree 0. After creating \mathit {in}, we can initialize Z in \Theta (V) time: iterate through the vertices and add each v to Z if \mathit {in}[v] = 0.
At each iteration, we pop/dequeue a vertex u from Z in \Theta (1). To "delete" u, we don't actually need to delete it from any graph data structure; it's enough to decrement \mathit {in}[v] for each edge u \to v, and add v to Z if \mathit {in}[v] becomes zero. This is \Theta (1) per edge and only looks at each edge once in total. Hence the entire algorithm is \Theta (V+E) overall.
Algorithm Kahn's Algorithm [00NI]
- September 24, 2026
The resulting algorithm is known as Kahn’s Algorithm, and was first published by Arthur Kahn in 1962.
Kahn's Algorithm analysis [00PF]
- October 16, 2026
How long does Kahn's Algorithm take?
- Creating T, Z, and \mathit {in} each take \Theta (1).
- Initializing \mathit {in} (the first \mathsf {for} loop) takes \Theta (V+E) since we loop over all vertices and then look at every edge once.
- Initializing Z (the second \mathsf {for} loop) takes \Theta (V), assuming we can add to Z in \Theta (1) time.
- The main \mathsf {while} loop will execute \Theta (V) times; in each loop we do some \Theta (1) operations (remove from Z, append to T), and do \Theta (1) work for each of several edges. Again, we will look at each edge once in total, so this main loop takes \Theta (V+E) time.