Algorithms Fall 2026 lecture notes [00JF]
These are my lecture notes for CSCI 382, Algorithms for the Fall 2026 semester.
Problems to be solved can be found here.
Here is a list of the algorithms we have studied.
Advanced/optional material [advanced]
Some sections of the notes may be marked with a star (★). This indicates optional, more advanced material which is included for the sake of those who are interested. Such material may or may not be presented in class and will not be formally assessed.
Introduction to POGIL/CSCI 382 [00JG]
- August 6, 2026
We used an activity to introduce POGIL and the syllabus for CSCI 382.
Why POGIL? [00JT]
- August 28, 2026
Via another activity, we learned about the two main aspects of POGIL:
- Guided Inquiry Learning: working in a team on an activity designed to guide you through a learning process.
- Process-Oriented: through the roles, the activities also help you develop process skills such as communication, critical thinking, information processing, and teamwork.
Brute force algorithms [00JJ]
- August 26, 2026
Introduced via a POGIL activity. Some key takeaways:
- In this class we will consider solving problems with specified inputs and outputs.
- A brute-force algorithm is one that simply lists all possible outputs for the given inputs and checks which one has the desired properties.
- This semester we will consider a lot of clever ways to solve problems faster than brute force. But that's not always possible.
The Euclidean Algorithm [00JU]
- August 31, 2026
The first algorithm we will consider is the famous Euclidean algorithm for finding the greatest common divisor of two integers. We name it after Euclid, who wrote it down in his classic work on geometry and number theory, The Elements; however, it has been reinvented in multiple times, places and cultures throughout history.
Review: mod and GCD [00JV]
- August 31, 2026
The material in this section is presented via a POGIL activity.
For a refresher on the \mathbin {\mathbf {mod}} operator, see these lecture notes from Discrete Math.
For a refresher on GCD, see these lecture notes.
The Euclidean Algorithm, recusively and iteratively [00K2]
- September 2, 2026
The material in this section is also presented via a POGIL activity.
We will consider two different implementations of the Euclidean Algorithm.
Algorithm Recursive Euclidean Algorithm [00K4]
- September 2, 2026
The first implementation of the Euclidean Algorithm is recursive:
Algorithm Iterative Euclidean Algorithm [00K5]
- September 2, 2026
The second implementation of the Euclidean Algorithm is iterative:
By trying examples, it seems like both these algorithms produce correct results. But how can we be sure? This is an important question, because it's easy to write versions of these algorithms which look very similar, and even work some of the time, but which sometimes crash, loop forever, or return an incorrect result!
Proving \mathsf {GCDR} correct [00K3]
- September 2, 2026
We will begin by formally proving the correctness of the recursive Euclidean Algorithm. But before we can even do that, we have to back up a bit: what does it even mean for an algorithm to be "correct"?
Specification vs implementation [00K6]
- September 2, 2026
Whenever we implement an algorithm, we have in mind a specification of what we would like the algorithm to achieve. This specification could be in the form of a mathematical definition (as in this case), or it could be a brute-force algorithm which "obviously" does what we want, or a table of inputs and outputs, or any other way of precisely defining a relationship between inputs and outputs. Our algorithm is then an implementation of this specification, and our job is to show that the specification and implementation match: that is, they produce identical outputs for all possible inputs.
In this case, the specification we have in mind is the mathematical definition of \gcd ; the implementation we have in mind is the \mathsf {GCDR} function. We are starting with \mathsf {GCDR} because it's usually much easier to prove things about recursive algorithms than about iterative ones!
In order to prove that \mathsf {GCDR} is correct, we first need two small lemmas about the mathematical \gcd function. The proofs are included only for completeness—feel free to skip them unless you are interested.
Lemma GCD is commutative [00F3]
- April 16, 2026
\gcd (a,b) = \gcd (b,a).
Proof.
- April 16, 2026
Theorem GCD reduction via mod [00F8]
- April 16, 2026
For all a,b \in \mathbb {N}, \gcd (a,b) = \gcd (a \mathbin {\mathbf {mod}} b, b).
Proof.
- April 16, 2026
By the division algorithm write a = bq + r. Then
Now we can prove that \mathsf {GCDR} matches its specification.
Theorem \mathsf {GCDR} is correct [00K8]
- September 3, 2026
For all a,b, \geq 0, \mathsf {GCDR}(a,b) = \gcd (a,b).
Proof.
- September 3, 2026
By (strong) induction on b.
- In the base case, when b = 0, \mathsf {GCDR}(a,0) = a, which is indeed the definition of \gcd (a,0).
- Now suppose b > 0 and that for all a, \mathsf {GCDR}(a,b') = \gcd (a,b') whenever b' < b. In this case \mathsf {GCDR}(a,b) = \mathsf {GCDR}(b, a \bmod b). We know a \bmod b < b, so the induction hypothesis applies (note in particular that the induction hypothesis holds for any a, and in particular we can pick b as our “a”). We concude that \mathsf {GCDR}(a,b) = \mathsf {GCDR}(b, a \bmod b) = \gcd (b, a \bmod b) = \gcd (a \bmod b, b) = \gcd (a,b), where the last two steps follow from the fact that \gcd is commutative and the previous lemma.
Proving \mathsf {GCDI} correct [00K9]
- September 3, 2026
Now let's prove that the iterative version of the Euclidean Algorithm is correct as well.
Theorem \mathsf {GCDI} is correct [00KB]
- September 3, 2026
\mathsf {GCDI}(a,b) = \gcd (a,b).
Proof.
- September 3, 2026
Suppose we initially call \mathsf {GCDI}(m,n). Then we claim the following loop invariant: each time right before doing the loop check again, \gcd (a,b) = \gcd (m,n). That is, the \gcd of the current values of a and b is always equal to the \gcd of the original arguments to \mathsf {GCDI}.
We prove this by induction on the number of loop executions.
- In the base case, before the loop has executed at all, a and b are equal to the original arguments to \mathsf {GCDI}, hence the invariant holds trivially.
- Otherwise, suppose the invariant held after n loop iterations; we must show it will still hold after one more loop iteration. But this follows from the theorem GCD reduction via mod.
Finally, after the loop ends, we will have either a = 0 or b = 0, and we can see that we will return wichever one is nonzero. This correctly returns the \gcd of a and b since \gcd (a,0) = a. But because of the loop invariant we know that \gcd (a,b) = \gcd (m,n), hence \mathsf {GCDI}(m,n) = \gcd (m,n).
It might seem like we are done, but actually we are not—we do not know that the loop will ever stop! All we have proved so far is that if it ever stops, it will deliver the correct value, but that is a big if. It's worth remarking that our proof of correctness for \mathsf {GCDR} neatly sidestepped this issue because it was by induction on the size of the arguments to \mathsf {GCDR}: the proof that the function returns the correct value, and the proof that the function always stops after a finite amount of time, were both wrapped up into a single argument. With \mathsf {GCDI}, we must argue these two things separately.
So, why does \mathsf {GCDI} always stop? Each time through the loop, either a gets smaller and b stays the same, or b gets smaller and a stays the same: if the loop starts out with a \leq b, then b gets smaller, since b \bmod a < a \leq b. Otherwise a gets smaller, since a \bmod b < b < a. Since neither ever gets bigger and one gets strictly smaller every loop iteration, one of them must eventually hit 0, which will stop the loop.
Technically, this argument that \mathsf {GCDI} always stops is a proof by well-founded induction on pairs \mathbb {N}^2 under the well-founded relation \{((a,b), (x,y)) \mid (a < x \land b = y) \lor (a = x \land b < y)\}.Remark. ★ Pedantic comment about well-founded induction, for those who like that sort of thing [00KC]
Euclidean Algorithm problems [00KF]
- September 4, 2026
Problems related to The Euclidean Algorithm, induction, and proving algorithm correctness.
[GCD1] GCD via factoring vs Euclidean algorithm (2 pts) [00JW]
- August 31, 2026
In class we considered the problem of finding the greatest common divisor of two positive integers. We explored two ways to compute the GCD:
- Factor the two numbers into their unique prime factorizations, and find the biggest subset of primes contained in both; this is the factorization of the GCD.
- Run the Euclidean Algorithm.
- Use your brain, a calculator, Wolfram Alpha, and/or some other appropriate computational system to factor 170520 into its prime factors.
- Now factor 522522, and use the results to find \gcd (170520, 522522) by Method 1.
- Trace the execution of the Euclidean Algorithm on (170520, 522522). Compare and contrast the two methods of computing the GCD of these two numbers.
- Now try to factor the number m shown below, using whatever methods you like (for example, try using Wolfram Alpha). What happens? m = 308903627938612635213051732991863520976852479109400884338832430641564115236537.
I would be willing to bet some money that you did not succeed in factoring m—though not a large amount, since there do exist algorithms that can factor numbers of this size in a matter of hours or even minutes; but in any case factoring a number with, say, four times as many digits as this would require more like centuries. Factoring is widely believed to be a rather difficult computational problem (the security of your bank account probably depends on it!).
- Now, suppose I tell you that there are in fact three prime numbers p, q, and r, such that \begin {align*} m &= p \cdot q = 308903627938612635213051732991863520976852479109400884338832430641564115236537 \\ n &= p \cdot r = 235051426595377535232357646935740625119338466495681619002059053022377525089111 \end {align*} (this is the same number m from part (d)). Find p, q, and r.
- What does this suggest about the relative efficiency of the two methods for computing the GCD?
[K4] Kattis: GCD (1 pt) [00JY]
- September 1, 2026
Solve GCD. You may not use any built-in GCD function; you must implement the Euclidean Algorithm yourself.
Runtime analysis of the Euclidean Algorithm [00KE]
- September 4, 2026
In [GCD1] GCD via factoring vs Euclidean algorithm (2 pts), you learned that the Euclidean Algorithm seems much more efficient than factoring; but how efficient is it, exactly? The problems in this section will walk you through a classic analysis of how long the Euclidean Algorithm takes to run on given inputs. However, the problems are independent; it is possible to do each problem without having done the previous ones.
Together, the problems in this section walk you through a proof of what is known as Lamé's Theorem, first proved by Gabriel Lamé in 1844. It was significant in being one of the first “practical” applications of the Fibonacci numbers, and one of the first results in what we would now call the theory of algorithms.
Throughout this section, when referring to the Euclidean
Algorithm, we will specifically work with the recursive
implementation \mathsf {GCDR} (GCDRecA from the POGIL activity).
[GCD2] GCD of consecutive Fibonacci numbers (2 pts) [00JZ]
- September 1, 2026
Recall the Fibonacci numbers, defined by F_0 = 0, F_1 = 1, and F_{n+2} = F_{n+1} + F_n. That is, the first two Fibonacci numbers are 0, 1, and then each subsequent Fibonacci number is the sum of the previous two, so the first few are 0, 1, 1, 2, 3, 5, 8, 13, \dots
- Compute F_9 and F_{10}, and trace the execution of the Euclidean Algorithm to compute \gcd (F_{10}, F_9). What happens?
- Prove by induction on n that \gcd (F_{n+1}, F_n) = 1 for all n \geq 0.
- Explain why your proof also shows that the Euclidean Algorithm requires n recursive steps to compute \gcd (F_{n+1}, F_n) = 1.
[GCD3] Worst-case GCD input (3 pts) [00K0]
- September 1, 2026
In fact, more is true: consecutive Fibonacci numbers (F_{n+1}, F_n) are in some sense a worst-case input for the Euclidean Algorithm: they are the smallest numbers for which the Euclidean Algorithm needs n steps.
Let S(n) be the following proposition:
S(n) = For all natural numbers a and b, if a > b and \mathsf {GCDR}(a,b) makes n recursive calls, then a \geq F_{n+1} and b \geq F_n.
That is, if R(a,b,n) represents the proposition "\mathsf {GCDR}(a,b) makes n recursive calls", then S(n) = \forall a,b : \mathbb {N}.\; ((a > b) \land R(a,b,n)) \to ((a \geq F_{n+1}) \land (b \geq F_n)).
- Prove \forall n : \mathbb {N}. S(n) by induction on n:
- What does the base case S(0) say? Prove it.
Hint.
- September 1, 2026
Look at the code for \mathsf {GCDR}. What can you conclude about a and b if it makes zero recursive calls?
- Let k be an arbitrary natural number, and prove S(k) \to S(k+1) by supposing S(k) to be true and proving S(k+1). You may want to write out S(k) and S(k+1) in full to help you keep track of what you know and what you are trying to prove.
Hint.
- September 1, 2026
Show that a \geq b + a \mathbin {\mathbf {mod}} b.
- What does the base case S(0) say? Prove it.
- Explain why the previous result shows that if a \leq F_{n+1} then the Euclidean Algorithm requires at most n steps.
[GCD4] Fibonacci number size (3 pts) [00K1]
- September 1, 2026
How big are Fibonacci numbers? Let’s find out:
- Solve x^2 = x + 1 for x and call the positive solution \varphi (this is often known as the golden ratio) and the negative solution \hat {\varphi }.
- Explain why we know that \varphi ^2 = \varphi + 1 and \hat {\varphi }^2 = \hat {\varphi } + 1.
Hint.
- September 1, 2026
Your answer should be one sentence!
- Show that \varphi ^{k+2} = \varphi ^{k+1} + \varphi ^k for all k \geq 0 (by starting with \varphi ^2 = \varphi + 1 and multiplying both sides by \varphi ^k). Note that the same is also true with \hat {\varphi } in place of \varphi .
- Now prove by strong induction on n that F_n = \frac {1}{\sqrt 5}(\varphi ^n -
\hat {\varphi }^n).
Hint.
- September 1, 2026
Don’t forget that you need two base cases; you will want to show that \varphi - \hat {\varphi } = \sqrt 5.
-
Conclude that F_n \approx \varphi ^n/\sqrt 5.
Hint.
- September 1, 2026
What can you say about \hat {\varphi }^n as n gets large?
[GCD5] Time complexity of the Euclidean Algorithm (logarithm review) (2 pts) [00KD]
- September 4, 2026
Suppose we want to run the Euclidean Algorithm to compute \gcd (a,b), assuming a > b. Let F_{n+1} be the smallest Fibonacci number which is greater than or equal to a. Then we know from the previous problem that the Euclidean Algorithm takes at most n steps to run, with the worst case being when a = F_{n+1}. We want to figure out how n relates to a.
Starting from a = F_{n+1} (since this is the worst case), and using the result from the previous problem, namely, that F_n \approx \varphi ^n/\sqrt 5, solve (approximately) for n in terms of a. Your final answer should be of the form n \approx k_1 \log _{10} a + k_2 for suitable constants k_1 and k_2; you should give k_1 and k_2 in approximate, decimal form. Conclude that the Euclidean Algorithm requires, in the worst case, a number of steps proportional to the number of digits in the base-ten representation of a.
[I2] Exponentiation (3 pts) [00KG]
- September 4, 2026
Write a recursive algorithm which, given a real number b and a natural number e, computes the power b^e. Prove that your algorithm is correct.
You may express your algorithm using appropriate pseudocode, or you may implement it in a real programming language; either one is fine. You may use addition, subtraction, multiplication, and division, but you may not use any kind of built-in exponentiation operation.
[I3] The Jellybean Game (3 pts) [00KI]
- September 8, 2026
The jellybean game is a game for two players. There is a row of n jars, numbered 1 to n from left to right, each of which starts out containing some number of jellybeans (possibly zero). We assume that these are magical jars which can hold an unlimited number of jellybeans, so we don’t have to worry about the jars getting too full. (Note, however, that the jars cannot hold infinitely many beans—each jar must always have some finite number of jellybeans in it, but that number can be as big as we want.) We also assume that there is an unlimited supply of extra jellybeans (such as a jellybean factory or a magical jellybean-pooping unicorn).
The players alternate turns. On a player’s turn, she must:
- Pick a nonempty jar, call it jar k.
- Remove one jellybean from jar k.
- Add as many jellybeans as she wants (possibly zero) to each of the jars 1 \dots (k-1) to the left of her chosen jar.
For example, suppose there are five jars which currently hold 1 \quad 3 \quad 0 \quad 2 \quad 6. One possible valid turn is to pick jar 4 and remove one jellybean from it, then add 6, 29, and one billion jellybeans to jars 1, 2, and 3 respectively, resulting in 7 \quad 32 \quad 10^9 \quad 1 \quad 6.
The winner is the player who removes the last jellybean. Put another way, the loser is the first player who is unable to move because all the jars are empty.
- Prove that the jellybean game always ends eventually. That is, even if the players conspire to try to make the game last forever, they cannot, as long as they follow the rules. (Of course, they certainly can make the game take a very, very long time...)
- Describe a winning strategy for the jellybean game. From which positions is the first player guaranteed to win, as long as they play perfectly? What strategy should the first player follow in order to guarantee a win, if a win is possible?
Asymptotic Analysis [00K7]
- September 3, 2026
The basic concepts of asymptotic analysis are introduced in a POGIL activity.
Why asymptotic analysis? [00KN]
- September 9, 2026
Why should we examine problems analytically at all? For example, why not just run programs and use a stopwatch to compare them?
- Actually running programs might take too long!
- The analysis lets us analyze problems for all input sizes at once, rather than having to gather data points.
- The analysis is independent of the algorithm implementation, the language in which the program is implemented, and the architecture in which the program is run. We insulate ourselves to all these variables.
- Theoretically efficient almost always implies practical efficiency.
Intuition and motivation for big-O [00KR]
- September 9, 2026
From now on, we’ll assume that n \geq 0, T(n) \geq 0, and that T represents a generic function \mathbb {N} \to \mathbb {R} representing, say, the amount of time an algorithm takes to run on an input of size n. Recall that big-O is “like \leq ”, big-Omega is “like \geq ”, and big-Theta is “like =”. However, if we were to define, say, big-O as “T(n) is O(n^2) if T(n) \leq n^2”, that would be too restrictive for us. For one thing, we don’t want it to matter what computer we run things on. What if it takes 2n^2, or 3n^2? Those are not actually \leq n^2, but we want them to be considered “the same as” n^2. Also, we don’t really care what happens for small values of n (after all, for small values we could just run the algorithm ourselves, by hand), so it’s not necessary that T(n) \leq n^2 (or some multiple) for all values of n, only that it be so eventually. These considerations lead to the following formal definition.
Definition Big-O [00KO]
- September 9, 2026
T(n) is O(g(n)) iff there exists a real constant c > 0 and a natural number n_0 \geq 0 such that for all n \geq n_0, T(n) \leq c \cdot g(n).
Definition Big-Omega [00KP]
- September 9, 2026
The definition of big-Omega is identical, except that we use \geq in place of \leq :
T(n) is \Omega (g(n)) iff there exists a real constant c > 0 and a natural number n_0 \geq 0 such that for all n \geq n_0, T(n) \geq c \cdot g(n).
Definition Big-Theta [00KQ]
- September 9, 2026
T(n) is \Theta (g(n)) iff T(n) is both O(g(n)) and \Omega (g(n)).
Remark [00KS]
- September 9, 2026
Note this is not the same as replacing the \leq in the definition of big-O with an = sign! In that case, T(n) would have to be exactly equal to some constant multiple of g(n), which would be much too restrictive. In the actual definition, T(n) must merely fall in between two different constant multiples of g(n).
Definition Little-o [00KX]
- September 9, 2026
T(n) is o(g(n)) iff T(n) is O(g(n)) but not \Theta (g(n)).
Remark [00KY]
- September 9, 2026
In other words, intuitively, T(n) is o(g(n)) if it grows strictly more slowly than g(n). For example, n+2 is o(n^2).
Example [00KT]
- September 9, 2026
Consider T(n) = 3n^2 + 17n + 8. To show that this is O(n^2) according to the definition, we can reason as follows: \begin {align*} T(n) &= 3n^2 + 17n + 8 \\ &\leq 3n^2 + 17n^2 + 8n^2 \quad (n \geq 1) \\ &= 28n^2 \end {align*} So we can choose c = 28 and n_0 = 1, which satisfies the definition, so T(n) is O(n^2). (In fact we could also pick c = 4 along with a bigger n_0.)
Remark Big-O in the real world [00KU]
- September 9, 2026
A lot of the time people use big-O when what they really mean is \Theta . In this class we will be very careful to use them properly. It’s useful to have all of them at our disposal. For some problems we know exactly how fast they can be solved, so we use \Theta . For some problems we know some O and some \Omega but they are not the same. For example, matrix multiplication: we know it must take \Omega (n^2) time, and there are algorithms that show it is O(n^{2.37\dots }), but no one knows what the theoretical limit is (we will look at matrix multiplication later in the semester).
Limit theorems [00KV]
- September 9, 2026
It is usually really annoying to use these definitions directly. Instead we can often compare rates of growth using limits. Note in the below that L < \infty is used as a shorthand to mean "the limit L exists and does not diverge to \infty ", and L = \infty is used as a shorthand to mean "the limit L diverges to \infty ".
Theorem Asymptotic bounds via limits [00KW]
- September 9, 2026
- If 0 \leq \lim _{n \to \infty } T(n)/g(n) < \infty then T(n) is O(g(n)).
- If 0 < \lim _{n \to \infty } T(n)/g(n) \leq \infty then T(n) is \Omega (g(n)).
- If 0 < \lim _{n \to \infty } T(n)/g(n) < \infty then T(n) is \Theta (g(n)).
- If \lim _{n \to \infty } T(n)/g(n) = 0 then T(n) is o(g(n)).
Remark [00KZ]
- September 9, 2026
Note that the converse is not true, since, for example, T(n) might be O(g(n)) even if the limit does not exist. As a counterexample, let T(n) = 0 when n is even, and 1 when n is odd. Then T(n) is O(1) but \lim T(n)/1 does not exist. But typically this won’t be an issue with the functions we will see in this class!
Arithmetic with big-O [00L0]
- September 9, 2026
The following properties hold for \Omega and \Theta as well.
- k O(f) = O(f) when k is a constant, i.e. does not depend on n
- O(f) + O(g) = O(\max (f,g)) (running algorithms in sequence)
- O(f) O(g) = O(fg) (running nested algorithms)
For example, O(3n^2 + 17n + 8) = O(3n^2) + O(17n) + O(8) = O(n^2) + O(n) + O(1) = O(n^2).
Time Complexity Zoo [00L1]
- September 10, 2026
We now present a “complexity zoo”, with examples of things having each common asymptotic time complexity, with some relevant facts interspersed. Our zoo will be ordered from smallest to biggest; that is, each entry will be little-o of the next thing. For each \Theta (f(n)), we will also record the largest n such that we can process an input of size n using a \Theta (f(n))-time algorithm in approximately 1 second, assuming we can do 10^8 operations per second.
\Theta (1): constant (any input) [00L2]
- September 10, 2026
A \Theta (1) or constant time algorithm is one whose running time does not depend on the size of its input. If we have an algorithm that takes \Theta (1), we can obviously process arbitrary-sized inputs in less than one second.
Examples of \Theta (1) operations include:
- Access an arbitrary index in an array
- Push to or pop from the top of a stack
- Add to or remove from the end of an extensible list (e.g.
ArrayListin Java; Python lists) - Insert, update, or remove from a hash table (e.g.
set+ dictionaries in Python;HashSet/HashMapin Java) - Add to or remove from either end of a deque (double-ended queue)
- Arithmetic (usually! sort of!)
\Theta (\lg n): logarithmic (unimaginably large inputs) [00L3]
- September 10, 2026
We say something is logarithmic if it is proportional to \log n for inputs of size n.
Notation \lg [00L4]
- September 10, 2026
We will use \lg n as an abbreviation for \log _2 n. Two is by far the most common and useful base for logarithms when talking about computers.
If we have an algorithm that takes \Theta (\lg n) time, we could use it to process inputs of size 2^{10^8} in one second, which is unimaginably large.
Examples of things that are \Theta (\lg n):
- Binary search
- The height of a balanced binary tree with n nodes
- The number of bits needed to represent n
Theorem Logarithm base doesn't matter to \Theta [00L9]
- September 11, 2026
\Theta (\log _a n) = \Theta (\log _b n) for all positive real numbers a and b. In other words, up to \Theta , the base of a logarithm doesn't matter; \Theta (\log n), \Theta (\lg n), \Theta (\ln n), etc. are all the same.
Proof.
- September 11, 2026
Theorem Logarithms grow more slowly than any power [00L8]
- September 11, 2026
\log _b n is o(n^x) for all x > 0 and any b > 1.
Proof.
- September 11, 2026
Remark \lg n is much closer to 1 than n [00LA]
- September 11, 2026
This is somewhat surprising! \Theta (\lg n) is actually smaller than n to any positive power: even \Theta (\sqrt [15]{n}) or whatever. \Theta (\lg n) is not “halfway between” \Theta (1) and \Theta (n); in some sense it is much closer to \Theta (1).
For example, the biggest number that fits in a 64-bit integer is about 10^{19}. How long would it take to count that high? At 10^8 per second, it would take 10^{11} seconds or about 3000 years. But if we can process it using something that repeatedly halves, \lg 10^{19} \approx 63.
\Theta (\sqrt n) = \Theta (n^{1/2}) (inputs up to 10^{16}) [00LB]
- September 11, 2026
This will not come up much in this course, but it is definitely a thing. See “square root decomposition”.
\Theta (n): linear (inputs up to 100 million) [00LC]
- September 11, 2026
Examples of things that are \Theta (n):
- Linear search
- Maximum/minimum/sum of a list
- Merge two sorted lists
- Insert or removing at the beginning of an array/list.
\Theta (n \lg n) (inputs up to 4.5 million) [00LD]
- September 11, 2026
Examples of things that are \Theta (n \lg n):
- Mergesort, quicksort
- In general, divide & conquer algorithms with \Theta (n) work at each level. We’ll study this in more detail later in the semester.
- If you are only allowed to compare pairs of elements to see which is greater, sorting a list of n elements takes \Omega (n \lg n). In other words, it's impossible to sort any faster than n \lg n if you are only allowed to compare elements. (If you are allowed extra operations, sorting faster than n \lg n is possible; for example, a list of integers can be sorted in \Theta (n) time.)
\Theta (n^2): quadratic (inputs up to 10 thousand) [00LE]
- September 11, 2026
Examples of things that are \Theta (n^2):
- Two nested loops (often, but not necessarily)
- 1 + 2 + 3 + \dots + n = \frac {n(n+1)}{2} = \Theta (n^2)
- The number of pairs of items chosen out of n, \binom {n}{2} = \frac {n(n-1)}{2}.
- Repeatedly appending n characters to a string one by one
- Insertion sort, bubble sort
\Theta (n^k) (inputs up to \sqrt [k]{10^8}) [00LF]
- September 11, 2026
\Theta (2^n): exponential (up to n = 26) [00LH]
- September 11, 2026
Examples of things that are \Theta (2^n):
- Number of subsets of n things
- Number of bitstrings of length n
- Number of nodes (also number of leaves) in a tree of height n
- 1 + 2 + 4 + 8 + \dots + 2^n = 2^{n+1} - 1, so it is \Theta (2^n)
Theorem [00LI]
- September 11, 2026
n^k is o(r^n) for all integers k \geq 0 and real numbers r > 1.
Proof.
- September 11, 2026
Remark Polynomial vs exponential [00LJ]
- September 11, 2026
There is an insurmountable gulf between polynomial and exponential time. For example, even n^{295} is o(1.001^n)! We usually take this to be the dividing line between “efficient/feasible” and “inefficient/infeasible”. (Of course n^{295} is probably not actually feasible but in practice we don’t see algorithms with running times like that.)
\Theta (n!): factorial (inputs up to 11) [00LK]
- September 11, 2026
n! corresponds to the number of distinct orderings of n things. If an algorithm takes \Theta (n!) it is really, really bad. In fact, k^n is o(n!) for all k.
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.
Greedy Algorithms [00NJ]
- September 28, 2026
Introduction [00NK]
- September 28, 2026
Our next unit covers greedy algorithms—an important class of algorithms where repeatedly making the locally best choice (i.e. a "greedy" choice) results in a globally best result. This does not always work—but when it does, it is very effective. Typically, to prove that greedy algorithms are correct we can use some kind of exchange argument, where we imagine exchanging the greedy choice for some other choice, and show that it could only possibly make the result worse.
Weighted graphs [00NP]
- October 2, 2026
So far we have considered undirected and directed graphs, but each edge either exists or not. We will now consider weighted graphs, where each edge has some sort of cost.
Definition Weighted graph [00NN]
- October 2, 2026
A weighted (directed or undirected) graph is a graph where each edge is assigned a weight. That is, formally, there is a function w : E \to W which assigns to each edge e \in E a weight w(e) taken from a suitable set of weights W. The weight of an edge (u,v) is also denoted w(u,v) or w_{uv}.
The weight or length of a path is just the sum of the weights of its edges.
Remark ★ What kind of things can we use for weights? [00NO]
- October 2, 2026
For now, we will typically consider the set of weights W = \mathbb {R}^+, that is, nonnegative real numbers; later, we will consider W = \mathbb {R} and include the possibility of negative weights.
In general, one can use other sets besides real numbers for weights. For example, we could use integers, or natural numbers, or rational numbers. In fact, one can use any ordered semiring: there must be two operations corresponding to combining weights in series and in parallel (typically, for finding shortest paths, we combine weights in series by adding them, and in parallel by taking the minimum), these two operations must play nicely together, and there must also be some notion of "less than" which also plays nicely with the operations.
Remark Unweighted graphs as weighted graphs [00NQ]
- October 2, 2026
Note that we can usually think of an unweighted graph as a weighted graph where all edges have weight 1.
Dijkstra's Algorithm [00NL]
- September 28, 2026
The basic ideas behind Dijkstra's algorithm are first introduced via a POGIL activity.
Single-Source Shortest Paths [00NW]
- October 3, 2026
Dijkstra's Algorithm solves the single-source shortest path (SSSP) problem in a directed, weighted graph: given a vertex s, find the shortest paths from s to every other vertex in the graph.
Note that this seems like a harder problem than just finding the shortest path from s to some particular target vertex t, but it's really not. Intuitively, you can’t find the shortest path from s to t without exploring the rest of the graph, thus discovering shortest paths from s to other vertices along the way.
Dijkstra's Algorithm intuition [00NX]
- October 3, 2026
In an unweighted graph, we can use BFS to find shortest paths, but now we need to take edge weights into account. Intuitively, BFS searches outwards one layer at a time, by increasing distance. We’ll do the same thing: search outward by increasing distance. Imagine turning on a source of water at vertex s, and watching the water flood the whole graph. Each edge is a (directed) pipe, and the weight of an edge says how long the water takes to traverse that pipe. We can keep track of "where the water has reached" so far, and note at each step the next vertex reached by the water. Since the water floods in every direction possible, it is guaranteed that the time the water first reaches a vertex corresponds to the shortest path to that vertex from s.
Note that this only makes sense when the edge weights are positive—if water can “travel back in time” it invalidates this whole scheme; we can’t necessarily find the next vertex to be reached by the water with a greedy approach. If we want to find shortest paths when edge weights can be negative, we need a different algorithm (which we will study later).
Algorithm Dijkstra's Algorithm (basic version) [00NY]
- October 3, 2026
Here’s the basic algorithm, which we can think of as a generalization of BFS to weighted graphs. Recall that BFS keeps track of:
- which vertices have been visited so far,
- a layer map, giving the layer of each visited vertex, and
- a parent map recording the parent of each vertex in the BFS tree.
Theorem Correctness of Dijkstra's Algorithm [00NZ]
- October 3, 2026
Dijkstra’s algorithm correctly solves the SSSP problem for a weighted graph with nonnegative edge weights.
Proof.
- October 3, 2026
- At the start of the algorithm, s is the only visited vertex, and d[s] = 0 is correct since there are no negative-weight edges (and hence no better way to get from s to itself than just staying there).
- Now suppose the invariant holds and the loop executes one more time. Let u, v be the vertices picked by the algorithm. We will show that any other path from s to v must be at least as long as the path from s to v via u. Any other path from s to v must cross from a visited vertex to an unvisited vertex at some point, say it does this on the edge x \to y. But by the way u and v were chosen, we know that the shortest path from s to y via x is at least as long as the path from s to v (since by the invariant we know the shortest path from s to x), plus there may be extra distance from y to v as well. (Notice how the assumption of nonnegative edge weights is important here—if the distance from y to v could be negative it invalidates this proof!)
Hence, the loop updates the set of visited vertices and d appropriately and the invariant still holds.
Running time of Dijkstra's Algorithm (basic) [00O0]
- October 3, 2026
How long does the basic version of Dijkstra's Algorithm take? It depends a lot on how we choose vertices u and v on each iteration. A brute-force approach is to simply iterate over all edges (u,v), keep only those where u is visited and v unvisited, and remember the one with the smallest value of d[u] + w_{uv}. Since the while loop marks one vertex visited on each iteration, it executes |V| times, making the whole algorithm \Theta (VE) (which could be O(V^3) if the edges are dense). However, it turns out we can do better than this if we use a more clever scheme for quickly finding the best edge at each iteration. (Note that the best algorithms for solving the SSSP problem where negative weights are allowed run in \Theta (V^3) or \Theta (VE); we will learn about one such algorithm later in the semester.)
More efficient Dijkstra's algorithm [00O2]
- October 5, 2026
Can we do better than \Theta (VE)? The key, as usual, is to use some data structures to keep track of enough information so that we can pick u and v quickly without having to search through the whole graph every time.
Priority queue for Dijkstra [00O3]
- October 5, 2026
- We will expand d to keep track of not just the shortest distances to vertices, but the current shortest known distances to other vertices as well. So d[v] will always be an upper bound on the shortest distance from s to v. We may have to update d[v] every time we add a vertex u to S with an edge (u,v).
- We will expand the \mathit {parent} map similarly: \mathit {parent}[v] is the predecessor of v along the currently shortest known path from s.
The idea is that at each iteration we want to pick the unvisited vertex v with the smallest d[v]. We will store the unvisited vertices in some kind of data structure so that we can quickly remove the one with the smallest d[v]. We then need to be able to update d and \mathit {parent} appropriately.
So we need a data structure that allows us to:
- Add new items with a given value
- Remove the item with the smallest value
- Update the value of an existing item
Algorithm Dijkstra's Algorithm [00O4]
- October 5, 2026
Here is the updated version of Dijkstra's Algorithm using a priority queue for tracking unvisited vertices.
Remark Dijkstra in practice [00O5]
- October 7, 2026
Most standard libraries I am aware of do not have a priority queue implementation capable of doing a fast \mathit {updateKey} operation. One can simply remove an element and re-insert it, but this takes \Theta (n) since there is no way to find an element other than scanning over the entire heap. An implementation supporting a fast \mathit {updateKey} could, for example, keep a hash table on the side which keeps track of the location of each item within the heap. Given a sorted set data structure, it is also possible to keep a sorted set of (distance, vertex) pairs. Removing the vertex with the minimum distance is easy since it is just the first pair in the set; updating the distance of a vertex can be done by first deleting the (old distance, vertex) pair from the set (which can be done in O(\lg n) since the set is sorted) and then inserting (new distance, vertex).
Dijkstra runtime analysis [00O6]
- October 7, 2026
What’s the time complexity of this better implementation of Dijkstra's Algorithm? Again, we can’t just simplistically look at loops and so on. Instead, we count the total time taken by various operations. Let’s say our priority queue takes time T_{\mathit {rem}}(n) to do a remove-min operation on a priority queue of size n, and T_{\mathit {upd}}(n) to do an update-key operation.
- For any reasonable implementation of Q, creating it in the first place takes \Theta (V) time since we are inserting vertices with known keys all at once.
- We end up calling \mathit {removeMin} once for each vertex, and Q has size at most |V|, which contributes \Theta (V \cdot T_{\mathit {rem}}(V)) (the priority queue decreases each time, but half the calls are on a priority queue of size at least V/2, so we are still justified in saying it takes \Theta (V \cdot T_{\mathit {rem}}(V))).
- We also call \mathit {updateKey} at most once for each edge, which contributes O(E \cdot T_{\mathit {upd}}(V)).
- All other operations (e.g. setting values in d and \mathit {parent}) take \Theta (1), which adds \Theta (V + E) overall.
So in total, the algorithm takes \Theta (V \cdot T_{\mathit {rem}}(V) + E \cdot T_{\mathit {upd}}(V)). We’ll generally assume that |E| \geq |V| (otherwise the graph is either a tree, in which case we don’t need this algorithm, or there are degree-zero vertices which we can throw away). The total running time depends on the implementation of Q:
- We could simply use an array of vertices. Finding and removing the vertex with the smallest d value thus takes \Theta (n) (via linear search); updating the distance value also takes \Theta (n) since we have to do another linear search to find the required vertex. Substituting, this yields an overall time of \Theta (V \cdot V + E \cdot V) = \Theta (EV) (since we are assuming |E| \geq |V|).
- We could keep the array sorted by d value. Assuming we keep the vertex with the smallest d value at the end, removing it can be done in \Theta (1). To update the distance of a vertex requires a linear search to find the vertex and then linear time to insert it into its new sorted position. Thus overall this is \Theta (V \cdot 1 + E \cdot V) = \Theta (EV), no better than an unsorted array.
- We could use a dictionary (implemented as an array or hash table) mapping each vertex to its distance value. Updating is now \Theta (1), since we can just immediately access the value for a given vertex. However, finding and removing the vertex with minimum distance is \Theta (n) since we have to just scan through all the vertices to find the minimum. Overall, this takes \Theta (V \cdot V + E \cdot 1) = \Theta (V^2) (since E is O(V^2)).
- If we use a binary min-heap to store vertices by distance, we can remove the smallest-distance vertex in \Theta (\lg n). Updating a specific vertex is a bit tricker: we can keep some kind of hash table on the side so we know where to find a given vertex in the heap; then moving it up or down the heap to restore the heap properties after changing the distance value takes \Theta (\lg n). Hence, overall, Dijkstra with a binary heap takes \Theta (V \lg V + E \lg V) = \Theta (E \lg V).
- Finally, there is a data structure called a Fibonacci heap which allows updating in \Theta (1) and removing the minimum in \Theta (\lg n), in which case Dijkstra takes \Theta (V \lg V + E) overall. We won't learn more about Fibonacci heaps but you can read about them if you wish.
Technically, using a Fibonacci heap yields the fastest known implementation of Dijkstra's Algorithm, but Fibonacci heaps are complex to implement and rarely make a big difference in practice. \Theta (V \lg V + E) is better than \Theta (E \lg V) only if E is large relative to V, that is, if the graph is fairly dense. Using a binary heap tends to be the best all-around implementation.
Minimum spanning trees [00O7]
- October 9, 2026
Some of the information in this section is presented via two POGIL activities: Minimum Spanning Trees, Kruskal's Algorithm and the Cut Property.
Motivation [00O8]
- October 9, 2026
Suppose we have a number of vertices (locations, items, people, ...) and potential connections between them, where each connection has a cost (distance, money, ...). We want to pick some of the potential connections such that all vertices are connected, but the total cost is as small as possible.
For example, suppose there are a number of cities, and we can build train lines between certain pairs of cities for some particular cost. Some train lines might be more expensive (because they have to go over mountains, or over a bridge, or because they are very long) and some might be cheaper. What is the minimum amount of money we can spend building train lines such that it is possible to travel between any pair of cities by train?
These ideas suggest the following definitions.
Spanning subgraphs and minimum spanning trees [00O9]
- October 9, 2026
Definition Spanning subgraph [00OA]
- October 9, 2026
Let G = (V,E) be an unweighted graph with vertices V and edges E. A spanning subgraph of G is a connected graph V,E' where E' \subseteq E.
That is, a spanning subgraph of G is a connected graph with the same vertices as G and a subset of the edges; to make a spanning subgraph of G we pick some edges which connect all the vertices.
Remark Observations about spanning subgraphs [00OB]
- October 9, 2026
A few observations about spanning subgraphs:
- If G is connected, then G is a spanning subgraph of itself.
- If G is disconnected, it has no spanning subgraph, because deleting edges can't make it connected.
- If a spanning subgraph of G contains a cycle, then removing any edge from the cycle results in another spanning subgraph.
Definition Minimum-weight spanning subgraph [00OC]
- October 9, 2026
A minimum-weight spanning subgraph (MWSS) of an undirected, weighted graph G is a spanning subgraph with the smallest possible total weight.
Remark A graph can have multiple MWSS [00OD]
- October 9, 2026
Note that a graph can have multiple minimum-weight spanning subgraphs. For example, consider a triangle graph where all the edges have weight 1. Picking any two of the edges results in a minimum-weight spanning subgraph.
It turns out that if every edge has a unique weight, then the MWSS is unique, although this is not necessarily obvious!
Remark A MWSS does not contain shortest paths! [00OE]
- October 9, 2026
It is worth emphasizing that although a MWSS contains a path between any two vertices, that path may not be the shortest path. The MWSS is guaranteed to have the smallest total weight, but for individual pairs of vertices the path between them may be longer than necessary, because it allows us to connect all the vertices in the most efficient way overall.
As an example, consider a triangle graph T with three edges of weights 2, 2, and 3. To make an MWSS, we obviously want to pick the two edges of weight 2. But notice that the shortest path in T between the two endpoints of the weight-3 edge is of length 3, whereas the path between them in the MWSS has total length 4.
Theorem Every MWSS is a tree [00OF]
- October 9, 2026
In a weighted, undirected graph with positive edge weights, any minimum-weight spanning subgraph must be a tree.
Proof.
- October 9, 2026
Subproof. Every MWSS is a tree ›
- October 9, 2026
Subproof. Every MWSS is a tree ›
- October 9, 2026
Definition Minimum spanning tree [00OG]
- October 9, 2026
Because of the previous theorem, a minimum-weight spanning subgraph is usually referred to as a minimum spanning tree, or MST.
Algorithms for computing MST [00OH]
- October 9, 2026
Here are three algorithms to compute a minimum spanning tree:
- Kruskal's Algorithm: repeatedly pick the shortest edge that doesn't complete a cycle with other already-picked edges.
- Prim's Algorithm: repeatedly pick the shortest edge that connects a visited vertex to an unvisited vertex and doesn't complete a cycle.
- Reverse-delete: repeatedly delete the longest edge that doesn't disconnect the graph.
It's kind of amazing that all these greedy approaches work. It's almost like we can't mess it up no matter what we try. But how do we know that they work?
Proving MST algorithms correct [00OI]
- October 9, 2026
Proving the correctness of all the algorithms mentioned above relies on one crucial property.
Definition Cut [00OL]
- October 9, 2026
A cut in a graph G = (V,E) is a partition of the vertices V into two sets S and T, that is, every vertex is in either S or T but not both. We say that an edge e crosses the cut (S,T) if one vertex of e is in S and the other is in T.
Theorem Cut property [00OJ]
- October 9, 2026
Let G = (V,E) be an undirected, weighted graph with positive weights. Suppose S and T partition V, and let e = (x,y) be an edge crossing the (S,T) cut, such that the weight of e is strictly smaller than the weight of any other edge crossing the (S,T) cut. Then every minimum spanning tree of G must contain e.
Proof.
- October 9, 2026
Let G be a weighted, undirected graph G = (V,E), let S and T be an arbitrary partition of V into two sets, and suppose e = (x,y) is the smallest-weight edge with one endpoint in S and one in T. We wish to show that any MST of G must contain e.
We will prove the contrapositive. Suppose M is a spanning tree of G which does not contain the edge e; we will show that M is not a minimum spanning tree. Since M is a tree, it contains a unique path between any two vertices. So consider the unique path in M between x and y. It must cross the cut at least once since it starts in S and ends in T; suppose it crosses at e' = (x',y'),with x' \in S and y' \in T. We know that the weight of e is smaller than the weight of e', since e was defined to be the smallest-weight edge crossing the (S,T) cut. Now take M and replace e' with e; the result is still connected (because any path using e' can be rerouted through e), but it has a smaller total weight because the weight of e is less than e'.
So, we have shown that any spanning tree M which does not contain the edge e can be made into a smaller one, which means that M is not a minimum spanning tree.
Remark Exchange arguments [00OK]
- October 9, 2026
This is an exchange argument, which is a general technique for proving that something is not minimal (and, more generally, for proving that greedy algorithms are correct)—find appropriate things to exchange so the total becomes smaller (while preserving any relevant properties).
In this particular example, note that we can’t exchange e with any edge across the cut! We particularly found the edge on the path from x to y since that guarantees we can exchange it with e while preserving connectivity.
Theorem Kruskal's Algorithm is correct [00OM]
- October 9, 2026
Kruskal’s Algorithm is correct (when all edges have distinct weights).
Proof.
- October 9, 2026
Remark Kruskal on graphs with repeated weights [00ON]
- October 9, 2026
The previous theorem applies only to graphs where every edge has a distinct weight, but it is not too much harder to show that Kruskal's Algorithm works even when there are repeated weights.
Remark Prim and Reverse-Delete are correct [00OP]
- October 9, 2026
Prim's Algorithm and the Reverse-Delte algorithm are correct as well, by similar arguments.
Implementing Kruskal's Algorithm with Union-Find [00OW]
- October 12, 2026
Let's consider Kruskal's Algorithm more carefully. Here it is again, in pseudocode:
Algorithm Kruskal's Algorithm (pseudocode) [00OX]
- October 12, 2026
Analysis of naive Kruskal [00P1]
- October 14, 2026
How fast can Kruskal's Algorithm run? First of all, sorting the edges takes \Theta (E \lg E) time if we use a good sorting algorithm. Note that E is O(V^2) (the maximum number of edges is V(V-1)/2), so \lg E is O(\lg V^2) = O(2 \lg V) = O(\lg V). Hence we can simplify \Theta (E \lg E) to \Theta (E \lg V).
The rest depends a lot on how we check whether an edge e would complete a cycle. One obvious method is to do a graph search like DFS or BFS from one endpoint of e, using only edges already in T, and see if we can reach the other endpoint of e. If there is a path from one end of e to the other using only edges in T, it means that adding e would complete a cycle. Running a DFS or BFS in T takes \Theta (V + E) = \Theta (V) (since T will never have more edges than vertices), and we do this check once for each edge, giving a total of \Theta (VE), which dominates the \Theta (E \lg V) time to sort the edges. Of course, \Theta (VE) can be as big as \Theta (V^3) if there are a lot of edges. Can we do better?
Union-find motivation [00P2]
- October 14, 2026
Notice that for each edge e = (u,v), doing a DFS is sort of overkill, in the sense that it actually tries to find a path from u to v—but we don’t care about the path, only whether u and v are already connected or not. In this case—when we only care about which vertices are connected and not about the actual paths between them—it turns out that we can test for connectivity much faster.
The basic idea is to come up with some sort of data structure to maintain a set of connected components. Given such a data structure, the algorithm looks something like this:
- Start every vertex in its own connected component.
- For each edge, test whether its vertices are in the same component (which means it would form a cycle) or in different components.
- If the endpoints are in different components, add the edge to T, and merge the two components into one.
This kind of data structure is called a union-find structure (or a disjoint-set data structure), and from the algorithm sketch above we can see what operations it needs to support:
- \mathsf {MakeSets}(n): create a union-find structure containing n singleton sets labelled 0 \dots n-1.
- \mathsf {Find}(v): return the name of the set containing v. (“Name” could be anything; typically we will use integers.) To check whether two vertices u and v are in the same connected component, we can test if \mathsf {Find}(u) = \mathsf {Find}(v).
- \mathsf {Union}(x,y): merge the two sets containing x and y.
This kind of data structure actually has lots of applications besides implementing Kruskal's Algorithm; you can explore one such application on a homework problem.
Algorithm Kruskal's Algorithm (with union-find) [00P3]
- October 14, 2026
Given a union-find data structure, we can implement Kruskal's Algorithm as follows:
Analysis of Kruskal with union-find [00P4]
- October 14, 2026
Let's analyze this version of Kruskal's Algorithm with union-find, to discover how fast we would like the union-find operations to be!
- Sorting edges by weight takes time \Theta (E \log V), as before.
- We do 2E \mathsf {Find} operations, because we call it twice for each edge to check whether adding that edge would make a cycle.
- We only call \mathsf {Union} when adding an edge, and since we are making a tree, we will do this at most V - 1 times.
Union-find design and analysis [00PD]
- October 15, 2026
We previously introduced the idea of a union-find structure; we will now see how to actually implement it efficiently.
Some bad ideas for implementing union-find [00P5]
- October 14, 2026
How can we implement a union-find data structure? One simple idea is to just keep a dictionary that maps each item to an "id" which identifies which set it is in.
- \mathsf {Find} takes \Theta (1), assuming we can do \Theta (1) dictionary lookup (e.g. using a hash table).
- To do \mathsf {Union}, however, we have to go through every single item to find which ones are in the set we want to change, and change them all to the other set. This takes \Theta (n), which is too slow.
We could also try to flip things around and keep a dictionary mapping each set id to a list of items in that set.
- \mathsf {Union} is now \Theta (1) (assuming we use something like linked lists), since we can just append one list to the other.
- However, \mathsf {Find} is now \Theta (n): to find an item we simply have to go through every list looking for it.
Can we somehow get the best of both worlds?
Idea: union-find via "lazy ids" [00P6]
- October 14, 2026
It turns out that the first idea above (having a dictionary mapping every item to an id for its set) is a good starting place. \mathsf {Union} took too long since we had to update every single item in a set to reference a new set. But what if we didn't have to update all of them?
We can do this if we allow ourselves a bit of indirection: rather than having every item reference its set, we can have every item either reference its set or another item in the same set. Imagine arranging all the items in a set into a tree: the item at the root is the only one that directly references the identity of the set (in fact, we can use the root item itself as the "name" of the set, like naming a group after its leader); every other item references some other item in the set, but ultimately if we keep following references we always end up at the root. Now, in order to change the identity of a set, we only need to update the root item itself; all the other items just "come along for the ride".
Union-find implementation [00PC]
- October 15, 2026
Based on the above ideas, we can implement a union-find structure as follows.
- We keep track of an array/dictionary mapping each item to its parent. Any item which maps to itself is considered a "root". This represents a forest, that is, a collection of trees; each tree consists of items which are all in the same set.
- We also keep track of an array/dictionary mapping every root item to the height of its tree. Tracking the heights of the trees is important so that we can implement union in a reasonable way. Non-root items will be ignored, so it does not matter what they map to. In other words, once an item stops being a root, we will stop worrying about keeping its height updated.
Given these mappings, we can implement the union-find operations as follows.
- To create a fresh union-find structure, create the parent dictionary mapping every item to itself (since every item starts in its own singleton set), and the height dictionary mapping every item to 0 (every item is the root of its own trivial tree of height 0).
- To implement \mathsf {Find}(u), repeatedly finding the parent, grandparent, etc. of u until finding a root.
- To implement \mathsf {Union}(u,v):
- Use \mathsf {Find} to get the roots of u and v’s trees.
- If the roots are the same, do nothing.
- If the roots are different, make the root with the smaller height the child of the root with the bigger height. If the heights are the same, it doesn’t matter which becomes a child of the other, but you must then increment the height of the new parent.
Union-find analysis [00PE]
- October 15, 2026
How long do these operations take? Clearly \mathsf {Union} takes T_{\mathsf {Find}} + \Theta (1). So implementing \mathsf {Find} efficiently is the crux of the issue. It seems like it might take \Theta (n) in the worst case, if we end up with an unbalanced tree—for example, if all the items in a tree end up in a long linear chain. But it turns out that being careful in how we implement \mathsf {Union}, taking heights into account, means this will never happen! The following theorem tells us something about what the resulting trees can look like.
Theorem Union-find trees are balanced [00PG]
- October 16, 2026
If we start from a freshly created union-find structure and call \mathsf {Union} any number of times (with the implementation outlined above), every tree of height h contains at least 2^h items.
Proof.
- October 16, 2026
Subproof. Union-find trees are balanced ›
- October 16, 2026
Subproof. Union-find trees are balanced ›
- October 16, 2026
For the induction case, suppose that any tree of height k contains at least 2^k items; we must show this is also true for trees of height k+1.
So suppose there is a tree of height k+1. The way \mathsf {Union} works, the height associated with a root only increases (by exactly one) when forming the union of two trees that previously had the same height. So the tree of height k+1 was, at some point, formed from the union of two trees of height k. By the induction hypothesis, those trees contained at least 2^k items each; hence the new, merged tree of height k+1 has at least 2^k + 2^k = 2^{k+1}. There could have been additional union operations since that one, but they could only increase the number of items.
Corollary \mathsf {Find} and \mathsf {Union} run in \Theta (\lg n) [00PH]
- October 16, 2026
\mathsf {Find} (and hence \mathsf {Union}) takes time \Theta (\lg n) in the worst case.
Proof.
- October 16, 2026
Remark Path compression [00PI]
- October 16, 2026
One can also implement path compression: when doing \mathsf {Find}, update every node along the search path to point directly to the root. This does not make \mathsf {Find} asymptotically slower, and it speeds up subsequent \mathsf {Find} calls. One can show (although the proof is somewhat involved—it would probably take two lectures or so) that \mathsf {Find} then takes essentially \Theta (\lg ^* n) on average, where \lg ^* n is the iterated logarithm of n, defined as the number of times the \lg function must be iterated on n before reaching a result of 1 or less. This means that the largest number for which \lg ^* n = k is n = 2^{2^{2^{\ldots }}} with k copies of 2 stacked up in a tower of exponents! So, for example, \lg ^* n \leq 5 for all n \leq 2^{2^{2^{2^2}}} = 2^{2^{2^4}} = 2^{2^{16}} = 2^{65536}, a number with 19729 decimal digits (for comparison, the number of particles in the entire universe is estimated at around 10^{80}, a number with a measly 81 decimal digits). So although in theory \lg ^* n is not a constant—it does depend on n, and can get arbitrary large as long as n is big enough—in practice, in our universe, it is essentially a constant (and a rather small constant at that). This means that both \mathsf {Find} and \mathsf {Union} can be implemented to run in (essentially) constant time!
Note, however, that this does not change the asymptotic running time for Kruskal’s algorithm, which is still dominated by the \Theta (E \log V) time needed to sort the edges.
Divide and Conquer [00PJ]
- October 19, 2026
The next standard problem-solving strategy we will consider is divide and conquer.
Divide and conquer introduction [00PK]
- October 19, 2026
Divide and conquer is a typical problem solving strategy that works as follows:
- Break up the input into (smaller) subproblems.
- Solve the subproblems recursively.
- Combine the subproblem solutions into an overall solution.
- To implement a divide-and-conquer strategy, we can use recursion.
- To prove the correctness of a divide-and-conquer strategy, we can use proof by induction.
- To analyze the asymptotic runtime of a divide-and-conquer strategy, we can use recurrence relations and the Master Theorem.
Divide and conquer example: Mergesort [00PL]
- October 19, 2026
The material in this section is presented via a POGIL activity.
A classic example of a divide-and-conquer algorithm is mergesort, which works by splitting the input list into two halves, recursively sorting each half, and then merging the sorted halves together.
Algorithm Mergesort [00PP]
- October 19, 2026
Mergesort analysis [00PQ]
- October 19, 2026
How long does mergesort take on a list of length n? Looking at the code above, we can see that
- It takes \Theta (1) in the base case (a list of length \leq 1).
- Otherwise, it makes two recursive calls to itself on lists of length approximately n/2.
- After the recursive calls complete, it does \Theta (n) additional work to merge the two sorted lists into a single sorted list.
If we draw out a tree showing all the recursive calls of \mathsf {mergesort} on an initial input of length n, it looks something like this:
The expression at each node indicates both the size of the input to that recursive call, as well as the amount of work which happens at that node (since the amount of work at each node is linear). We can see that- The tree has height \lg n, since we divide the input in half at each level until reaching a base case of 1.
- There is n total work happening at each level: n = n/2 + n/2 = n/4 + n/4 + n/4 + n/4 = \dots .
Divide and conquer example: multiplication [00PR]
- October 21, 2026
The material in this section is presented via a POGIL activity.
Another classic place where divide-and-conquer comes up is in trying to multiply large numbers faster than the naïve algorithm you learned in grade school.
Motivation [00PS]
- October 21, 2026
In many situations, when we use arithmetic operations on integers such as addition or multiplication, we simply assume they take constant time. This is appropriate when the integers are bounded by some fixed size, e.g. if all the integers are 64-bit integers. However, if we want to be able to deal with integers of arbitrary size, this is no longer appropriate; we must take the size of the integers into account. For example, as of October 20, 2026, the largest known prime number is 2^{136\,279\,841} - 1, a number with 41\,024\,320 decimal digits. The arithmetic operations needed to test this number for primality take a nontrivial amount of time!
n-bit addition [00PT]
- October 22, 2026
Adding two n-bit numbers is easily analyzed: we iterate through, starting with the ones place, and add the bits in each place (possibly doing another addition for a carry bit), for a total of about 2n bit operations in the worst case. Hence we know it is possible to add two n-bit numbers in linear time, so the worst-case time to add is O(n). However, it is also clearly \Omega (n), since we have to at least look at every bit in the input. Hence, adding n-bit numbers takes \Theta (n) time.
Naïve n-bit multiplication [00PU]
- October 22, 2026
What about multiplication? Using the standard "grade school" algorithm to compute p \times q, we end up with a shifted copy of p for every 1 bit in q, and then we must add then all. So there are up to n shifted copies of p to add, with each being at most 2n bits, so this particular algorithm will take \Theta (n^2) in the worst case.
However, unlike addition which obviously takes \Omega (n) time, it is not so obvious that multiplication must take \Omega (n^2) time. In fact, if anything, it is the opposite: it seems like adding up a bunch of shifted copies of the same bitstring might involve some redundant work. Perhaps there is a way we can multiply two n-bit numbers in faster than quadratic time.
Divide and conquer multiplication [00PV]
- October 22, 2026
Given an n-bit number X (and assuming n is even), we can split X into two halves X_1 and X_2, each with n/2 bits. We can express this as X = 2^{n/2} X_1 + X_2 since multiplying by a power of two performs a bit shift, i.e. adding zeros to the end of a number in binary (just like multiplying by a power of ten adds zeros to the end of a number in decimal—and for the same reason).
Remark What if n is odd?
- October 22, 2026
Note that we can still do something similar if n is odd—for example we can write X = 2^{\lceil n/2 \rceil } X_1 + X_2 where X_2 is one digit longer than X_1 (or we can imagine "padding" X_1 to length \lceil n/2 \rceil by adding a zero digit on the left).
If we have two n-bit numbers expressed in this form and multiply them, we get AB = (2^{n/2} A_1 + A_2)(2^{n/2} B_1 + B_2) = 2^n A_1 B_1 + 2^{n/2}(A_1 B_2 + A_2 B_1) + A_2 B_2. On the left-hand side we have a single n-bit multiplication; on the right-hand side we have four n/2-bit multiplications, two shifts, and three n-bit additions. We can turn this into a recursive algorithm for computing the product AB, something like the following:
(This works when n is a power of two; it is not hard (though a bit fiddly) to generalize to any value of n.)
Analysis of naïve divide-and-conquer multiplication [00PX]
- October 23, 2026
This divide-and-conquer multiplication algorithm involves four recursive calls to \mathsf {mul} on inputs of size n/2, two shifts (which take constant time), and three n-bit additions (which take \Theta (n)). Hence we can write a recurrence for the time M(n) taken by \mathsf {mul} on n-bit inputs: \begin {align*} M(1) &= \Theta (1) \\ M(n) &= 4M(n/2) + \Theta (n) \end {align*} But what is a closed form for M(n)? Is it better than n^2?
We can unroll this recurrence into a recursion tree to figure out how much total work happens.
- At the root, an amount of work happens proportional to the input size, n.
- At the first level of recursion, there are four recursive calls, each on n/2-bit numbers, giving a total something like 4 \cdot (n/2) = 2n.
- At the second level, there are sixteen recursive calls on n/4-bit inputs, giving a total of 4n.
- In general, at depth k, there are 4^k recursive calls, each on an input of size n/2^k, for a total of 4^k \cdot n/2^k = 2^k n.
The Master Theorem [00PY]
- October 23, 2026
Adding up the total work in a recursion tree for divide-and-conquer algorithms can be generalized to a powerful theorem known as the Master Theorem. (It is not named for someone; it is just a powerful theorem that "masters" a very wide range of divide-and-conquer algorithms. This is especially true when considering its generalizations such as the Akra-Bazzi method.)
Theorem Master Theorem [00Q1]
- October 23, 2026
If T(n) = a T(n/b) + \Theta (n^d) for positive constants a, b, and d, then T(n) = \begin {cases} \Theta (n^d) & \text {if } a < b^d \\ \Theta (n^d \log n) & \text {if } a = b^d \\ \Theta (n^{\log _b a}) & \text {if } a > b^d. \end {cases}
Remark Master theorem intuition [00Q5]
- October 23, 2026
Intuitively, a tells us how fast the number of recursive calls grows; b^d tells us how fast the problems are getting smaller. The ratio of these will end up being the common ratio of a geometric sum.
- If a < b^d, then the problems get smaller faster than the number of problems increases, and the total amount of work is dominated by the work done at the very top of the recursion tree.
- If a > b^d, then the number of nodes is growing faster than the work decreases, so the amount of work is dominated by the bottom level of the tree (as in our integer multiplication example).
- If a = b^d, then the growth of the number of subproblems is exactly balanced by the decrease in the amount of work, so there is exactly the same amount of work done in total at each level of the recursion tree (namely, O(n^d)), and the overall total is hence this amount of work per level times the number of levels (as in merge sort).
Remark Master theorem generalizations [00Q6]
- October 23, 2026
The Master Theorem can be generalized in a number of ways (for example, T(n) can be less than or equal to the right-hand side instead of equal; we can handle more complex expressions for the amount of extra work besides just \Theta (n^d); n need not be evenly divisible by b; and so on). I have presented the simple core of the idea here, and if you were to ever need a generalized version for some reason, you could look it up.
Before we get to the proof of the theorem itself, we will need a few small lemmas.
Lemma Log powers [00PZ]
- October 23, 2026
For any real numbers a,b > 1 and x > 1, a^{\log _x b} = b^{\log _x a}.
Proof.
- October 23, 2026
Lemma Asymptotic behavior of geometric series [00Q0]
- October 23, 2026
For some positive real constant r and any natural number n, let S = 1 + r + r^2 + \dots + r^n.
- If 0 < r < 1, then S is \Theta (1).
- If r = 1, then S is \Theta (n).
- If r > 1, then S is \Theta (r^n).
Proof.
- October 23, 2026
- If r < 1, then the infinite sum 1 + r + r^2 + \dots converges to the constant value \frac {1}{1-r}. The partial sum up to k is less than this, so it cannot depend on n either.
- If r = 1, then S = 1 + 1 + 1 + \dots + 1 = n+1, which is \Theta (n).
- If r > 1, then S = \frac {1 - r^{n+1}}{1 - r} = r \cdot r^n + \frac {1}{r-1} which is \Theta (r^n).
Proof of the Master Theorem [00Q7]
- October 23, 2026
We now have the tools we need to prove the Master Theorem.
Proof.
- October 23, 2026
- The tree has height \log _b n.
- A node at level k has size n/b^k and does (n/b^k)^d work.
- There are a^k nodes at level k, so the total work at level k is a^k \cdot \left (\frac {n}{b^k}\right )^d = n^d \left (\frac {a}{b^d}\right )^k.
Hence the overall total work is \sum _{k=0}^{\log _b n} n^d \left (\frac {a}{b^d}\right )^k = n^d \sum _{k=0}^{\log _b n} \left (\frac {a}{b^d}\right )^k. This is n^d times a geometric series with ratio a/b^d.
- If a < b^d then the ratio is < 1 and the sum is a constant; hence the total work is \Theta (n^d).
- If a = b^d then the ratio is 1 and the sum is \Theta (\log _b n); hence the total work is \Theta (n^d \log n).
- If a > b^d then the ratio is > 1 and the sum is proportional to its final term, (a/b^d)^{\log _b n}. In that case the total work is \Theta \left ( n^d \cdot \left (\frac {a}{b^d}\right )^{\log _b n} \right ) = \Theta \left ( n^d \cdot \frac {a^{\log _b n}}{(b^{\log _b n})^d}\right ) = \Theta (a^{\log _b n}) = \Theta (n^{\log _b a}).
Algorithm Karatsuba's Algorithm [00Q8]
- October 23, 2026
Now, back to n-bit integer multiplication! In 1960 it seemed “obvious” that integer multiplication was \Omega (n^2); Andrey Kolmogorov (a very prominent mathematician at the time) posed it as a conjecture. At a special seminar organized by Kolmogorov to investigate this conjecture and other related problems, a previously unknown 23-year-old graduate student, Anatoly Karatsuba, disproved the conjecture by coming up with a faster algorithm!
Break up A and B into two pieces of size n/2 as before: A = A_1 2^{n/2} + A_2 and B = B_1 2^{n/2} + B_2. Now for Karatsuba’s clever insight. Define \begin {align*} P_1 &= A_1 B_1 \\ P_2 &= A_2 B_2 \\ P_3 &= (A_1 + A_2)(B_1 + B_2) \end {align*} Note P_3 - P_1 - P_2 = A_1B_2 + A_2 B_1. Hence AB = P_1 2^n + (P_3 - P_1 - P_2) 2^{n/2} + P_2. This requires only three multiplications of size n/2! (Along with two additions of size n/2, four additions or subtractions of size n, and two shifts—more work than before, but all still \Theta (n) in total.)
Hence T(n) = 3T(n/2) + \Theta (n), so we can apply the Master Theorem with a = 3, b = 2, and d = 1. 3 > 2^1 so we are in the third case of the theorem (the work is concentrated at the bottom of the call tree), and we conclude that this algorithm is O(n^{\log _2 3}) \approx O(n^{1.59}).
This is not even the fastest known algorithm—for example, the Toom-Cook algorithm is a generalization of Karatsuba's algorithm which splits up the numbers into more than two pieces; and the fastest algorithm actually used in practice is the Schönhage-Strassen algorithm, which is based on different ideas (the Fast Fourier Transform) can multiply two n-bit integers in O(n \log n \log \log n). In 2019 it was even proved that it is possible to multiply two n-bit integers in \Theta (n \lg n) time, although the algorithm involved would not be faster in practice for any numbers that fit in our universe!
Median/Quickselect [00Q9]
- October 26, 2026
We will consider the \mathsf {Quickselect} algorithm as one final example of a divide & conquer approach.
Motivation [00QA]
- October 26, 2026
Consider the following problem: given a (not necessarily sorted!) array of n integers, find the median element (that is, the element which would be in the middle if the array were sorted).
One obvious solution is to first sort the array in \Theta (n \log n) time, and then simply access the array in the middle. However, intuitively it feels like this is doing too much work: we don’t actually care about the order of any of the other elements, so sorting them is a waste of time. Can we do better than \Theta (n \log n)?
Attempting divide & conquer [00QB]
- October 26, 2026
We consider a divide-and-conquer approach. First, if we simply split the list in half, it doesn’t seem to help much. We could find the median of both sides but there’s no way to compute the median of the whole list from the two medians. But simply splitting the list in half is not the only way to divide up a list. Since we were already thinking about sorting, what if we partition the list so that all the smaller elements are on one side and all the larger elements are on the other side? If we pick a random element as the pivot, we can partition the list into the elements less than the pivot on the left and greater than or equal to the pivot on the right, as in quicksort, in \Theta (n) time.
Now what? Simply finding the median of both sides still does not help. We can definitely say that the true median lies somewhere in between the left and right medians but that does not really help.
Generalize the induction hypothesis [00QC]
- October 27, 2026
The solution—as often with recursive algorithms—is to generalize to compute something more than what is required. In particular, instead of just finding the median element, let’s write an algorithm to select the element which would be at index k if the list were sorted. If we can do this, we can get the median by selecting the element at index \lfloor n/2 \rfloor . But this ability to select any element gives us the extra flexibility we need to use recursion to find the median, since the median of the entire list will not be the median of one of the two partitions, but some other index.
Algorithm Quickselect [00QD]
- October 27, 2026
\mathsf {Partition}(A) picks a random pivot value in A, and returns two lists: one containing all the values in A which are less than the pivot, and one containing all values greater than or equal to the pivot.
Note that in practice, one would implement this so it all works in-place on the array A, instead of generating new arrays A_1 and A_2, e.g. by passing along extra \mathit {hi} and \mathit {lo} parameters to specify which part of the array to focus on.
Theorem \mathsf {Quickselect} is correct [00QE]
- October 27, 2026
For any array A and any 0 \leq k < |A|, \mathsf {Quickselect}(A,k) correctly returns the element with order index k, that is, the element which would be at index k in a sorted version of A.
Proof.
- October 27, 2026
By strong induction on the size of A.
- When |A|=1, since 0 \leq k < |A| = 1, we must have k = 0. The algorithm returns A[0], which is indeed the item with index 0 in a sorted version of A, since a 1-element array is already sorted.
Otherwise, let |A| = n and assume as our induction hypothesis that (A',k') works correctly on any A' which is smaller than n.
Note that after the call to , all the elements in A_1 are smaller than all the elements in A_2. Put another way, if we sorted A, all the elements in A_1 would come first, followed by all the elements in A_2. Thus, if k < |A_1|, then the element of A with order index k falls somewhere within A_1, and in fact is the element of A_1 with the same order index. On the other hand, if k \geq |A_1|, then the order-index k element of A falls somewhere inside A_2. If k = |A_1| then we want the smallest element of A_2; if k = |A_1| + 1 then we want the second-smallest, and so on; in general, the kth smallest element of A will be the k - |A_1| smallest element of A_2. Since the IH tells us that the recursive calls to \mathsf {Quickselect} will correctly select these elements from A_1 or A_2, we conclude that \mathsf {Quickselect} is correct.
Theorem \mathsf {Quickselect} runtime analysis [00QF]
- October 27, 2026
\mathsf {Quickselect} runs in expected \Theta (n) time.
Proof.
- October 27, 2026
\mathsf {Quickselect} is a randomized algorithm, since the pivot value is chosen randomly; in theory we could make very bad pivot choices that would lead to bad performance. If the pivot is chosen randomly, however, we can expect that on average it will split the array into pieces which are 1/4 and 3/4 the size of the original array, respectively (or vice versa).
We can therefore analyze \mathsf {Quickselect} using the Master Theorem. We make one recursive call each time, so a = 1; in the worst case b = 4/3; and d = 1, since we spend \Theta (n) time partitioning A. Therefore a < b^d since 1 < 4/3, so this is the first case of the Master Theorem, and we conclude that \mathsf {Quickselect} takes \Theta (n^d) = \Theta (n) time.
Dynamic Programming [00QG]
- October 27, 2026
We now turn to study "dynamic programming"---which is really neither dynamic, nor programming (at least not in the current sense). The name was chosen by Richard Bellman in 1950 as something that sounded good to funding agencies; but the name stuck!
Previously we studied the divide and conquer technique, where a problem gets broken down recursively into subproblems. We’re still considering the same phenomenon—dynamic programming is about what to do when the recursive subproblems overlap. A naïve recursive implementation will thus end up being called on the same inputs multiple times, which is wasteful (sometimes dramatically so!). The basic idea is to save answers to recursive subproblems (memoization) so we don’t have to compute them more than once. Dynamic programming has a reputation for being difficult and confusing, but at heart it’s just this simple idea.
Dynamic programming example: Fibonacci numbers [00QH]
- October 27, 2026
We return to the Fibonacci numbers as a simple first example. Although dynamic programming is hardly necessary to compute Fibonacci numbers in reality, they still make for a nice illustrative example.
Naïve recursive Fibonacci [00QI]
- October 27, 2026
Recall the definition of the Fibonacci numbers:
The Fibonacci numbers are the sequence F_n defined by the recurrence
\begin {align*}
F_0 &= 0 \\
F_1 &= 1 \\
F_n &= F_{n-1} + F_{n-2}.
\end {align*}Definition Fibonacci numbers [00OZ]
# Fibonacci #1: naive recursive algorithm
def fib1(n):
if n <= 1:
return n
else:
return fib1(n-1) + fib1(n-2)Why is it so slow? If we draw the recursion call tree for, say, fib1(5), we can see the problem:
fib1(5) calls fib1(4) and fib1(3); but fib1(4) again calls fib1(3); and so on. fib1(1) ends up being called five times! If we were to start with a bigger number, it would be even worse.
The problem, then, is that fib1 spends a lot of time redundantly recomputing values that have already been computed before.
Memoization [00QJ]
- October 27, 2026
This is the core problem of dynamic programming: repeated recursive calls on the same input. The solution is memoization (note: not "memorization"!): creating some kind of data structure to remember previously computed outputs corresponding to given inputs, so that if the input is ever seen again the output can just be looked up without having to recompute it.
Dynamic programming technique 1: recursion with a memo table [00QK]
- October 27, 2026
The most direct thing we can do, therefore, is to keep our recursive function, but create a table in which we can save previously computed outputs. Every time the recursive function is called, we can check whether the answer for that input has already been computed and saved. If so, return it; if not, compute it recursively, save it, in the table, and return it.
# Fibonacci #2: recursion with memoization
# Global table of Fibonacci numbers; assume no one will
# ever call fib2(n) with n >= 1000
fib_table = [-1] * 1000
def fib2(n):
if n <= 1:
fib_table[n] = n
elif fib_table[n] == -1:
fib_table[n] = fib2(n-1) + fib2(n-2)
return fib_table[n]Even the first time it is called, fib2(n) runs in \Theta (n) time: each value in the table is computed at most once, and from then on it is simply looked up as needed without triggering any repeated recursive calls.
This approach is simple to code, and we don't have to worry about the right order in which to fill in the table; it will simply be filled in as needed. However, since we are just filling in a table anyway, one might wonder what the point is of using a bunch of recursion...
Dynamic programming technique II: filling in memo table directly [00QL]
- October 27, 2026
Once we recognize that the code in the previous section is essentially just filling in entries in a table, we can dispense with the recursion and simply use a loop to fill in the table directly.
# Fibonacci #3: explicitly filling in a table with a loop
def fib3(n):
fibs = [0] * (n+1) # Create initial array of all 0s
fibs[1] = 1
for i in range(2, n+1):
fibs[i] = fibs[i-1] + fibs[i-2] # Each fibs[i] is the sum of the previous two
return fibs[n]fib3(n) obviously runs in \Theta (n) time: it does \Theta (1) amount of work to fill in each entry in a table of size n.
This approach can be much more efficient in practice than using recursion; but we have to be careful to fill in the table in the correct order, so that we fill in each value only after all the values it depends on have been filled in.
Solving problems with dynamic programming [00QU]
- October 28, 2026
In general, here are the steps you should follow to solve a problem with dynamic programming:
- Try something else first! (Greedy, reduce to standard graph algorithm, ...)
- Consider different ways of splitting up or restricting the overall problem into subproblems or subcases, and come up with a recurrence. This is the hardest part! It does get easier with experience.
- Prove the recurrence correct (via induction).
- Check: do the recursive subproblems overlap?
- No: rejoice! You have a divide & conquer algorithm.
- Yes: proceed with the rest of the steps!
- Memoize the recurrence, either by adding a table to the recursive algorithm, or by directly filling in a table with some loop(s). Note that it is also possible to memoize with more exotic data structures (dictionaries, lazy infinite trees, ...) but in this class we will only see examples using arrays!
- Optional: to reconstruct an optimal solution, remember the choices made along the way, then reconstruct the solution in reverse. (We'll see examples of this later.)
Dynamic programming example: high+low stress jobs [00QV]
- October 28, 2026
Let's see how to apply this dynamic programming framework to a simple yet nontrivial problem. (The Fibonacci number example we started with was simple, yet also trivial, in the sense that we don't really need dynamic programming to compute Fibonacci numbers.)
Introduction [00QW]
- October 28, 2026
Consider the following table composed of n weeks where each week i has low stress job that pays L_{i} and a high stress job that pays H_{i}.
| WEEK | 1 | 2 | 3 | \dots | n |
|---|---|---|---|---|---|
| low stress | L_{1} | L_{2} | L_{3} | \dots | L_{n} |
| high stress | H_{1} | H_{2} | H_{3} | \dots | H_{n} |
Each week you are allowed to pick either a low stress job or a high stress job; however, picking a high stress job at week i means that you must first take the week before (i.e. week i-1) off. Your goal is to maximize your total income. Let’s suppose that you are allowed to take the high-stress job in week 1 (it doesn’t change the overall solution much either way, only the base case).
Greedy attempt [00QX]
- October 28, 2026
We've previously studied greedy algorithms, which is definitely the thing to try first. For example, one possible greedy algorithm is shown below.
This algorithm basically looks ahead one week and decides if it’s worth taking a week off in order to land a higher-paying job. However, this strategy fails, because taking a high stress job at week h_{i} means that you cannot take week h_{i} off to take a job at week h_{i+1}. Thus, any strategy employing look-ahead by a constant factor will fail. Here is a counter-example to the greedy algorithm.
| WEEK | 1 | 2 | 3 |
|---|---|---|---|
| low stress | 2 | 2 | 1 |
| high stress | 1 | 5 | 10 |
- The greedy algorithm chooses: 5 (week 2) + 1 (week 3) = 6
- However, the optimal solution is to choose: 2 (week 1) + 10 (week 3) = 12
High+low-stress job recurrence (+ proof) [00QY]
- October 28, 2026
The key to solving this problem is to come up with a recursive solution, and then use dynamic programming. The key idea (common to many similar problems) is to consider the most we could make if we worked only through week i and then stopped. That is, define \mathit {OPT}(i) = maximum revenue for working weeks 1 \ldots i. Now, we can come up with a recurrence for \mathit {OPT}:
- Base cases:
- \mathit {OPT}(0) = 0. We don’t make any money for working 0 weeks.
- \mathit {OPT}(1) = L_1. We can’t take the high-stress job the first week. (Or maybe we can, in which case \mathit {OPT}(1) = \max (L_1, H_1)—we need to clarify the problem parameters!)
- As our inductive/recursive case, \mathit {OPT}(k) = \max \begin {cases} L_{k} + \mathit {OPT}(k-1) \\ H_{k} + \mathit {OPT}(k-2)\end {cases} First, note that if we are going to maximize the profit for the first k weeks, we should always work the final week (there's no reason to take the week off to prepare for anything; we could always at the very least take the low-stress job). Thus, our decision is between working a high-stress or low-stress job in the final week. Choosing a low-stress job at week k means we should add L_{k} to the optimal profit for the previous k-1 weeks and choosing a high-stress job at week k means we had to take week k-1 off so we should add H_{k} to \mathit {OPT}(k-2). The optimal choice is to choose the max of these two options.
Notice that our arguments above actually constitute a proof by strong induction of the recurrence's correctness: we first argue why the base case(s) are correct, then argue why the recursive case for \mathit {OPT}(k) is correct (assuming, as our induction hypothesis, that \mathit {OPT} is already correct for any inputs < k).
Memoization and analysis [00QZ]
- October 28, 2026
We can see that naively computing \mathit {OPT}(n) using recursion would lead to many values of \mathit {OPT} being redundantly computed over and over—in fact, it has the same recursion pattern as the Fibonacci numbers. Thus, we must memoize.
Notice that \mathit {OPT} naturally forms a 1 \times (n+1) table where each entry requires \Theta (1) operations to fill in. We can use a recursive function that fills in the table as it goes, or we can just fill in the table using a loop from 0 up to n. Either way, the whole algorithm is obviously \Theta (n). This is one nice benefit of dynamic programming—analyzing the runtime of an algorithm using dynamic programming is usually dead easy!
Sample Python code for high+low-stress jobs [00R0]
- October 29, 2026
Here is how we might implement this algorithm in Python:
# low, high are lists of weekly salaries for low- and
# high-stress job, respectively.
def best_income(low, high):
n = len(low)
# Make low and high 1-indexed by adding dummy values to the
# beginning. This works much more nicely since we want M[i] =
# maximum for working i weeks, and M[0] = 0 is a natural base
# case, so we want to have the weeks be 1-indexed. (Adding extra
# "padding" elements to arrays to make room for base cases is a
# common technique with DP problems.)
low = [0] + low
high = [0] + high
# Initialize OPT[0..n] with all zeros.
OPT = [0] * (n+1)
# The first base case, OPT[0] = 0, is already taken care of.
# For OPT[1], just take the higher of the two jobs.
OPT[1] = max(low[1], high[1])
# Now loop through remaining weeks.
for i in range(2, n+1):
# How much could we make taking the low or high stress job?
low_total = low[i] + OPT[i-1]
high_total = high[i] + OPT[i-2]
# The optimal for weeks 1..i is the higher of the two
OPT[i] = max(low_total, high_total)
return OPT[n]
# Example:
# >>> best_income([2,2,1,7,5,20,3,19,10,13], [1,5,10,100,23,20,5,21,30,30])
# 182Remembering choices to reconstruct optimal job schedule [00R1]
- October 29, 2026
This solution tells us how much money we can make, but it doesn’t actually tell us which job we should take each week. However, it is not too hard to modify our solution to do this as well. The key observation is that during the algorithm, for each i, taking the max of two values corresponds to deciding which option would be better—to take the low- or high-stress job at week i. So we can just add another array, \mathit {JOBS}, to keep track of which decision leads to the best outcome at each week—that is, \mathit {JOBS}[i] records whether we should pick the low- or high-stress job at week i in order to maximize our income if we only work weeks 1 \dots i.
Note that \mathit {JOBS} does not directly tell us which jobs we should actually take to get the most money overall. For example, suppose \mathit {JOBS}[3] contains H. This means that if we only worked the first three weeks, then we should take the high-stress job in week 3. However, it may turn out that the best schedule overall has us working the low-stress job or taking week 3 off.
So, how do we actually reconstruct the optimal schedule for weeks 1 \dots n from \mathit {JOBS}? We just start at week n and work backwards, mirroring the recursive structure of \mathit {OPT}:
- If \mathit {JOBS}[n] = L, then we take the low-stress job in week n, and continue by looking at \mathit {JOBS}[n-1] to see what we should do the week before.
- If \mathit {JOBS}[n] = H, then we take the high-stress job in week n, take week n-1 off, and continue by looking at \mathit {JOBS}[n-2].
Sample Python code for high+low-stress jobs with optimal schedule reconstruction [00R2]
- October 29, 2026
Here is an enhanced version of the Python solution which computes the optimal schedule along with the optimal income:
def best_income(low, high):
n = len(low)
low = [0] + low
high = [0] + high
# Initialize an array of booleans to keep track of whether the
# optimal choice is to take the high-stress job at week i (if we
# only work weeks 1..i).
take_high_job = [False] * (n+1)
OPT = [0] * (n+1)
OPT[1] = max(low[1], high[1])
# We should take the high-stress job at week 1 iff it pays more.
take_high_job[1] = (high[1] > low[1])
for i in range(2, n+1):
low_total = low[i] + OPT[i-1]
high_total = high[i] + OPT[i-2]
OPT[i] = max(low_total, high_total)
# Record which choice produced the higher total
take_high_job[i] = high_total > low_total
# Now, to produce a work schedule, work backwards from the end
# Start at week n
w = n
schedule = []
while w > 0:
# If we should take the high-stress job at week w, schedule it
# and a week off, and proceed to look at week w-2 next
if take_high_job[w]:
schedule = ['off', 'HI'] + schedule
w -= 2
# Otherwise schedule the low-stress job and look at week w-1 next
else:
schedule = ['LO'] + schedule
w -= 1
return (OPT[n], schedule)
# Example:
# >>> best_income([2,2,1,7,5,20,3,19,10,13], [1,5,10,100,23,20,5,21,30,30])
# (182, ['off', 'HI', 'off', 'HI', 'LO', 'LO', 'LO', 'LO', 'off', 'HI'])Dynamic programming example: subset sum [00R9]
- November 6, 2026
As a slightly more involved example of dynamic programming, consider the following problem.
The subset sum problem [00RA]
- November 6, 2026
Given a set X = \{x_1, x_2, \dots , x_n\} of positive integers and a target value S, is there is a subset of X whose sum is exactly S?
Brute force subset sum solution [00RB]
- November 6, 2026
A brute force solution to the subset sum problem is to list every possible subset of X, sum each, and check whether any of them add to S. Naïvely, this takes \Theta (2^n) time to list every subset, and \Theta {n} time to sum each one, for a total of \Theta (n 2^n). (If we list the subsets in a clever order, we can arrange things so that only a single element is added or removed at each step, allowing us to update a running sum in only \Theta (1) per subset, for a total time of \Theta (2^n), but that's not all that much better.)
Recurrence for subset sum [00RC]
- November 6, 2026
The key to solving this problem is to generalize it along two dimensions: we consider both summing to any s \leq S, and we also consider trying to use only the x_i up to x_k, that is, \{x_1, \dots , x_k\}, instead of the full set X. That is, \mathit {canAddTo}(k,s) will be \mathsf {T} if there is a subset of \{x_1, \dots , x_k\} which adds to exactly s, and \mathsf {F} otherwise. We have the following recurrence: \begin {align*} \mathit {canAddTo}(k, 0) &= \mathsf {T} \qquad (\text {for all } k \geq 0) \\ \mathit {canAddTo}(0, s) &= \mathsf {F} \qquad (\text {for all } s > 0) \\ \mathit {canAddTo}(k,s) &= \begin {cases} \mathit {canAddTo}(k-1, s) & \text {if } x_k > s \\ \mathit {canAddTo}(k-1, s) \lor \mathit {canAddTo}(k-1, s - x_k) & \text {otherwise} \end {cases} \end {align*}
That is,
- We can always add to the sum 0 by picking the empty subset.
- We can never add up to a nonzero sum if we aren’t allowed to use any of the x_i.
- If x_k > s, then it can’t be used in a subset that sums to s, so whether we can make the sum s using a subset of x_1 \dots x_k has the same answer as whether we can make s using a subset of x_1 \dots x_{k-1}.
- Otherwise, we can try both omitting x_k (in which case we have to make s using elements up to x_{k-1}, as before), or using it (in which case we have to make the remaining s - x_k using the elements up to x_{k-1}).
Note that the above is essentially a proof by induction of the recurrence relation's correctness. We explained why the base cases are correct, and then explained why the recursive cases will compute the right thing, given the assumption that the recursive calls will return the correct answer when given smaller inputs.
Memoization for subset sum [00RD]
- November 6, 2026
This most definitely has overlapping subproblems. One simple approach is to use a 2D array c of size (n+1) \times (S + 1), so c[k][s] will store the output of \mathit {canAddTo}(k,s). It is also possible to use a dictionary with (k,s) pairs as keys; however, since 0 \leq k \leq n and 0 \leq s \leq S, using a 2D array is simpler and accomplishes exactly the same thing. (An array can be thought of as a special-purpose dictionary where the keys are consecutive integers starting from 0.)
Each entry depends only on entries either above it ( k is smaller), or above it and to the left ( k and s are both smaller), so we can fill it in row order or column order. In pseudocode:
Alternatively, we could use the technique of having a recursive function which checks first to see whether the required output is already in the array.
Since we fill in an (n+1) \times (S + 1) array, with \Theta (1) work required to fill in each cell, the algorithm takes \Theta (nS) time overall.
Remembering choices to reconstruct subset sum solutions [00RE]
- November 6, 2026
The above algorithm tells us whether it is possible to add to S via some subset, but it does not tell us what the actual subset is. To compute the actual optimal solution instead of just the optimal value, we can save the choices made at each step.
What information does \mathit {canAddTo} discard? It is precisely the choice of whether to use x_k or not. The Boolean “or” operation will be \mathsf {T} if either one of its inputs is; it does not care which. Therefore we will make another (n+1)\times (S+1) array of booleans called \mathit {use}, where \mathit {use}[k][s] is \mathsf {T} if and only if we should use x_k in a subset to make s. We initialize it to all \mathsf {F} values, and fill it in as shown in the pseudocode below.
If c[n][S] is , then there is some subset of X which adds to S. To reconstruct such an actual subset we can work our way backwards as follows:
★ Matrix chain multiplication [00RF]
- November 7, 2026
Matrix multiplication cost [00RG]
- November 7, 2026
Suppose we have matrices A and B, where A is p \times q and B is q \times r. (To be able to multiply them, the q has to match.) How many operations are needed to compute the matrix product AB?
- The result AB will be a p \times r matrix, so it has pr entries.
- To compute each entry of AB, we take a row of q entries from A and a column of q entries from B and multiply them, then add the results. So we do about q multiplications and q additions to compute each element of AB.
Thus, the total time to compute AB is O(pqr). Note that we can assume p, q, and r are small enough that fancy matrix multiplication algorithms like Strassen’s algorithm don’t really help.
Motivation [00RH]
- November 7, 2026
Matrix multiplication is associative, (AB)C = A(BC), but these may not take the same time to compute! Let’s try an example. Say
- A is 2 \times 10,
- B is 10 \times 3,
- and C is 3 \times 20.
It takes 10 \times 3 \times 20 = 600 operations to compute BC, resulting in a 10 \times 20 matrix. It would then take another 2 \times 10 \times 20 = 400 to compute A(BC), for a total of 1000. On the other hand, if we associate the product as (AB)C, it takes 2 \times 10 \times 3 = 60 operations to compute the 2 \times 3 matrix AB, and then only another 2 \times 3 \times 20 = 120 operations to compute (AB)C, for a total of 180—a big difference!
With just three matrices the situation is simple: we can easily just do these computations, compare, and choose the cheaper order. However, if we have a sequence of n matrices we wish to multiply, the situation is more difficult. For example, suppose we have six matrices A_1 \dots A_6 and want to compute their product. We could associate them, for example, as (A_1((A_2(A_3A_4))A_5))A_6, or as A_1(A_2(A_3(A_4(A_5A_6)))), or in fact in any of 42 distinct parenthesizations. We really don’t want to check all of them to see which would be the cheapest. In general, the number of parenthesizations for n matrices is the (n-1)st Catalan number C_n = \frac {1}{n+1}\binom {2n}{n} which for large n is approximately equal to C_n \sim \frac {4^n}{n^{3/2} \sqrt {\pi }}, so the number of possibilities becomes very large, very fast. The brute force algorithm—i.e. checking all parenthesizations to see which is best—is completely out of the question!
Matrix chain multiplication problem [00RI]
- November 7, 2026
Formally, we have a sequence of n matrices A_1, A_2, …, A_n, and a sequence of n+1 positive integers p_1, …, p_{n+1} such that matrix A_i has size p_i \times p_{i+1}. We want to compute the parenthesization of the A_i which minimizes the number of operations needed to compute the product A_1 \dots A_n. (Note that this generalizes readily to any situation where we have a sequence of n things and an associative binary operation where the cost of the operation varies depending on the arguments it is applied to.)
Recurrence for matrix chain multiplication [00RJ]
- November 7, 2026
The key observation is that ultimately, there will be some final two matrices that get multiplied to produce the final answer. These have to come from some splitting of the sequence of matrices into two subproducts (A_1 \dots A_k)(A_{k+1} \dots A_n). The total cost to compute the product if we split at index k is then given by the sum of the optimal cost to compute A_1 \dots A_k, the optimal cost to compute A_{k+1} \dots A_n, and the cost to do the final matrix multiplication, which will take p_1 p_{k+1} p_{n+1} operations (because (A_1 \dots A_k) is a p_1 \times p_{k+1} matrix, and (A_{k+1} \dots A_n) is a p_{k+1} \times p_{n+1} matrix). The best possible cost for the product A_1 \dots A_n will then be the minimum cost over all such splitting points k. In general, if we use m[i,j] to denote the minimum cost for computing the product A_i \dots A_j, with i \leq j, then we have the recurrence \begin {align*} m[i,i] &= 0 \\ m[i,j] &= \min _{i \leq k < j} (m[i,k] + m[k+1,j] + p_i p_{k+1} p_{j+1}) \end {align*} Note that m[i,i] = 0 since this corresponds to the base case of already having a single matrix A_i, so we do not need to do any work.
Memoization for matrix chain multiplication [00RK]
- November 7, 2026
We can store the m[i,j] values in an n \times n matrix (actually, we just need the part above the main diagonal since we assume i \leq j). Note that each m[i,j] depends on values to its left (m[i,k] where k < j) and below it (m[k+1,j] where k \geq i). So we can fill in the matrix by diagonals, beginning by filling in zeros along the entire main diagonal, then filling in values just above the main diagonal, then the second diagonal above the main diagonal, and so on. Note that the dth diagonal above the main diagonal consists of values of the form m[i,i+d], which corresponds to subproducts A_i \dots A_{i+d} of exactly d+1 matrices. So this seems intuitively sensible: first we compute the optimal way to multiply any two adjacent matrices; then we compute the optimal way to multiply any three adjacent matrices; then any four, and so on.
(Alternatively, we could arrange the matrix a bit differently, so that m[i,d] would denote the optimal cost for multiplying A_i \dots A_{i+d}. Then we would simply fill in the matrix by columns.)
Runtime analysis for matrix chain multiplication [00RL]
- November 7, 2026
The matrix m has size n \times n, and we need to fill in half its entries, giving a total of \Theta (n^2) entries to fill in. Each entry is computed as a minimum over at most n costs, each of which takes O(1) to compute (just a few lookups, additions, and multiplications). Thus the whole algorithm is O(n^3).
Reconstructing optimal matrix parenthesization [00RM]
- November 7, 2026
As usual, this recurrence gives us the optimal cost but doesn’t tell us what the actual best parenthesization is. This is a common issue with dynamic programming; the problem is that when we take the minimum over all k for each entry in the matrix m, we forget which k was best, recording only the best cost itself. The solution, therefore, is to maintain another n \times n matrix b which records the information that is otherwise being forgotten: b[i,j] records the “best split”, that is, the value of k (where i \leq k < j) which results in the minimum cost for the product A_i \dots A_j. After filling in the matrices m and b, we can reconstruct the best parenthesization (which is really just a binary tree) by recursively splitting starting from the top: we start by looking up b[1,n] = k which tells us where to do the top-level split (A_1 \dots A_k)(A_{k+1} \dots A_n). We then recursively look up b[1,k] and b[k+1,n] to find out where to make the next splits, and so on, until there are just single matrices left at the leaves of the tree.
The Floyd-Warshall algorithm [00RO]
- November 9, 2026
Introduction: all-pairs shortest paths and negative cycles [00RP]
- November 9, 2026
Recall that Dijkstra’s algorithm solves the single-source shortest path problem (i.e. it finds the shortest path from a single start vertex to every other vertex) for weighted, directed graphs, as long as all edge weights are positive. Today we will consider an algorithm to solve the all-pairs shortest path problem (that is, to find shortest paths between all possible pairs of vertices) on directed graphs with arbitrary (possibly negative) weights.
Of course, negative cycles can pose a problem: if there is a directed cycle whose total weight is negative, then we can keep decreasing the path weight forever by just going around the cycle. In that case “shortest” paths may not be well-defined. The algorithm we consider will also be able to detect this situation.
The All-Pairs Shortest Paths problem [00RQ]
- November 9, 2026
Input: a directed, weighted graph G = (V,E) with vertices numbered 1 \dots n. Output: an n \times n matrix s where s[u,v] records the length of the shortest path from u to v, or an indication that the graph has negative cycles.
Ideally we also want to be able to recover the actual shortest path between any two vertices u and v.
Recurrence for all-pairs shortest paths [00RR]
- November 9, 2026
We want to come up with a recurrence. As is typical, we add another parameter which we use to restrict the problem. In this case, we'll add a parameter k that means we are only allowed to use vertices 1 \dots k as intermediate notes. That is, we will let s[u,v,k] denote the length of the shortest path from u to v using only vertices 1 \dots k as intermediate nodes on the path.
As base cases, we consider k = 0, that is, we are not allowed to use any intermediate vertices. We have s[u,v,0] = \begin {cases} 0 & u = v \\ w_{uv} & (u,v) \in E \\ \infty & \text {otherwise} \end {cases} That is, if we are not allowed to use any intermediate vertices, the shortest path from a vertex to itself is 0, the shortest path from u to v along an edge is the weight of the edge, and the shortest path between vertices with no edge is \infty .
(Note that we can't say s[u,u,k] = 0 for k > 0, because there might be negative edges giving a "shorter" path from u back to itself!)
Now, what about the recursive case? Suppose for some k \geq 1 we already know s[u,v,k-1] for all u,v. Then how can we compute s[u,v,k]? There are two possibilities: either the best path from u to v goes through k, or it doesn’t.
- It could be that allowing vertex k does not help, in which case s[u,v,k] = s[u,v,k-1].
- If it does help, the best path from u to v will consist of first taking the best path from u to k (using only vertices 1 \dots k-1), followed by the best path from k to v: s[u,v,k] = s[u,k,k-1] + s[k,v,k-1]. (Note: the best path from u to v won’t go through vertex k twice, unless there is a negative cycle!)
The optimal cost will simply be the minimum of these two. That is, all together, we have \begin {align*} s[u,v,0] &= \begin {cases} 0 & u = v \\ w_{uv} & (u,v) \in E \\ \infty & \text {otherwise} \end {cases} \\ s[u,v,k] &= \min \begin {cases} s[u,v,k-1] \\ s[u,k,k-1] + s[k,v,k-1] \end {cases} \end {align*}
Reconstructing all-pairs shortest paths [00RS]
- November 9, 2026
To be able to reconstruct paths after the fact, we could do something similar to what we usually do: at each step we take a minimum over two choices, so we could keep a parallel 3D table \mathit {use}[u,v,k] that records whether we should use vertex k when trying to go from u to v using only vertices 1 \dots k. We could then use this to reconstruct the optimal path from u to v as follows: \mathit {bestpath}(u,v,k) = \begin {cases} \mathit {bestpath}(u,k,k-1) + [k] + \mathit {bestpath}(k,v,k-1) \\ \mathit {bestpath}(u,v,k-1) \end {cases} depending on whether \mathit {use}[u,v,k] is true (with some appropriate base cases as well).
However, for this problem it turns out we can do something a bit more clever using only a 2D array. In particular, let \mathit {next}[u,v] denote the next vertex after u in the shortest path from u to v that we have found so far. Then in the first case, when we set s[u,v,k] to s[u,v,k-1], we do not change \mathit {next}[u,v]; in the other case, we can update it as \mathit {next}[u,v] = \mathit {next}[u,k].
However, for this problem it turns out we can do something a bit more clever using only a 2D array. In particular, let \mathit {next}[u,v] denote the next vertex after u in the shortest path from u to v that we have found so far. Then in the first case, when we set s[u,v,k] to s[u,v,k-1], we do not change \mathit {next}[u,v]; in the other case, we can update it as \mathit {next}[u,v] = \mathit {next}[u,k]. Also, we don’t actually need to keep a 3D array for s. We can simply keep overwriting the same 2D array on each iteration of the loop. If we do that, it is no longer true that s[u,v] is exactly the shortest distance using only vertices 1 \dots k on the kth iteration—but if not it can only be shorter (if there are negative edges).
Algorithm Floyd-Warshall [00RT]
- November 9, 2026
After the algorithm is finished, to reconstruct the shortest path from u to v, we simply look up each step along the path using the \mathit {next} matrix. First we look up \mathit {next}[u,v] = u_2, then we look up \mathit {next}[u_2,v] = u_3, and so on, until reaching v.
Running time for Floyd-Warshall [00RU]
- November 9, 2026
What is the running time? It’s obviously \Theta (V^3)—just three nested loops from 1 \dots n. (Which seems kind of amazing given that there could be \Theta (V^2) edges and we need to find shortest paths between every pair of vertices, of which there are also \Theta (V^2).)
Floyd-Warshall and negative cycles [00RV]
- November 9, 2026
What about negative cycles? Well, just look at s[u,u]: u is part of a negative cycle if and only if s[u,u] (the length of the shortest path from u back to itself) is negative. Hence we can check whether there are any negative cycles in the graph in \Theta (n) time, by scanning along the diagonal of the matrix and looking for any negative numbers. It turns out with some extra work this can be extended to compute exactly which paths have some negative cycle along the way (and hence can be made as small as we want by going around the negative cycle) and which do not.
Generalizing Floyd-Warshall [00RW]
- November 9, 2026
As a fun aside, this algorithm is really cool because it can actually be generalized to work over any semiring instead of just (\min , +) (technically, any star-semiring), and it turns out that by appropriate choice of semiring, (a slight generalization of) the same algorithm can be used to do a great many things, such as find most reliable paths or largest capacity paths, count the number of shortest paths or total number of paths or even compute regular expressions for all possible shortest paths, compute transitive closures, invert matrices, solve linear systems of equations, or convert a DFA into a regular expression.
Network Flow [00RN]
- November 9, 2026
We now turn to study another important classical model with many (surprising!) applications, network flow.
Definition Flow network [00RX]
- November 11, 2026
A flow network is a directed graph G = (V,E) with
- a distinguished source vertex s \in V, with indegree 0;
- a distinguished target (or sink) vertex t \in V, with outdegree 0;
- a capacity function c : E \to \mathbb {N} assigning a non-negative integer capacity c(e) to each edge e \in E.
Capacities can easily be generalized to non-negative rational or even real numbers, but we will stick with integers.
★ Generalized weights [00RY]
- November 11, 2026
The weights in a weighted graph can be used to model various concepts. How we combine the weights—or even what type of values are used for the weights—depends on what we have in mind. In general, the important questions to ask about weights are:
- How do we combine the weights of two paths in series (i.e. when the two paths are sequenced end-to-end into a longer path)?
- How do we combine the weights of two paths in parallel (i.e. when we have two different paths between the same two start and end vertices)?
- How do we decide which of two weights is "better"?
For example, when weights represent a cost:
- We add the weights of two paths in series.
- We take the minimum of the weights of parallel paths.
- Smaller weights are better.
However, if weights represent a capacity, we might answer these questions differently:
- When paths are in series, we take the minimum weight: the smallest-capacity path is the bottleneck and determines the capacity of the whole composed path.
- When paths are in parallel, we either take the maximum (if we want to pick the higher-capacity path) or we add (if we are allowed to use both paths at once and we know the paths don't overlap at all).
- Bigger weights are better.
As another example, if weights represent some kind of probability, then we might multiply weights in series and take the maximum in parallel. Weights don't even have to be numbers! If weights are, say, strings, we might concatenate them in series and take the shorter of two strings in parallel (what would a "best path" mean in this context?).
We introcued algorithms like Dijkstra and Floyd-Warshall as algorithms to find shortest paths, but really they are algorithms for finding "best" paths: we can plug in any operations for combining weights we like (as long as they satisfy some nice algebraic properties like distributivity). For example, if we substitute the operations (\min , \max ) in place of (+, \min ), then Dijkstra and Floyd-Warshall find maximum-bottleneck paths: i.e. paths such that the minimum capacity along the path is as large as possible.
Definition Flow [00RZ]
- November 11, 2026
A flow on a flow network G is a function f: E \rightarrow \mathbb {N} assigning a natural number flow value to each edge, such that
- 0 \leq f(e) \leq c(e) for each edge e \in E (that is, the flow along an edge is limited by the edge’s capacity).
- What flows in must flow out: for each vertex (besides s and t), \sum _{e \text { entering } v} f(e) = \sum _{e \text { leaving } v} f(e).
We will abbreviate the above as f^{\mathrm {in}}(v) = f^{\mathrm {out}}(v).
Definition Flow value [00S0]
- November 11, 2026
The value of a flow f is defined as the amount of flow leaving the source: v(f) = f^{\mathrm {out}}(s).
Note that because the total flow must be preserved at each vertex, it should be intuitively clear that f^{\mathrm {out}}(s) = f^{\mathrm {in}}(t) so we could equally well define the value of a flow v(f) as the amount of flow arriving at the target. In fact, proving this formally is a good exercise.
Lemma ★ Flow value preservation [00S1]
- November 11, 2026
f^{\mathrm {out}}(s) = f^{\mathrm {in}}(t), that is, “what leaves s must eventually arrive at t”.
Proof.
- November 11, 2026
Note first that \sum _{v \in V} f^{\mathrm {out}}(v) = \sum _{e \in E} f(e) = \sum _{v \in V} f^{\mathrm {in}}(v). The middle sum is just the sum of the flows along every edge. But since every edge has exactly one start vertex, the flow along any given edge gets included exactly once in the left-hand sum (as part of f^{\mathrm {out}}(v) for its start vertex). Likewise, each edge is included exactly once in the right-hand sum, with its end vertex.
Since the left- and right-hand sums are equal, we have 0 = \left (\sum _{v \in V} f^{\mathrm {out}}(v)\right ) - \left (\sum _{v \in V} f^{\mathrm {in}}(v)\right ) = \sum _{v \in V} (f^{\mathrm {out}}(v) - f^{\mathrm {in}}(v)). But by definition of a flow (property 2), f^{\mathrm {out}}(v) - f^{\mathrm {in}}(v) = 0 for every vertex v other than s or t. Note also that f^{\mathrm {in}}(s) = 0 and f^{\mathrm {out}}(t) = 0. Hence everything in this sum cancels except f^{\mathrm {out}}(s) - f^{\mathrm {in}}(t). Thus we have shown f^{\mathrm {out}}(s) - f^{\mathrm {in}}(t) = 0, that is, f^{\mathrm {out}}(s) = f^{\mathrm {in}}(t).
Playing around with a few examples leads us to an obvious question.
Definition Max flow [00S2]
- November 11, 2026
The max flow problem asks, given a flow network G, what is the maximum possible value of a flow (and what is an example of such a maximum flow)?
Before presenting a solution to this problem, we will first explore some applications.
Applications of maximum flow [00SI]
- November 12, 2026
Maximum bipartite matching [00SJ]
- November 12, 2026
Definition Matching [00SK]
- November 12, 2026
Given an undirected graph G, a matching on G is a subset of edges such that no two edges share an endpoint. In other words, a matching on G is a way to match or "pair up" some of vertices.
A maximum matching is a matching which contains as many edges as possible.
Max bipartite matching via max flow [00TP]
- November 25, 2026
Finding maximum matchings for graphs in general is difficult, but it's much easier for bipartite graphs:
- Add a new source vertex s with an edge to each vertex in L.
- Add a new target vertex t with an edge from each vertex in R.
- Give every edge a capacity of 1.
- A valid flow of value k must have k units of flow going from L to R; since the edges all have capacity 1 there must therefore be k edges with flow on them. Moreover, none of them can share an endpoint since then two units of flow would have to enter or exit the same vertex, but this is impossible since the edges from s and the edges to t all have capacity 1 as well.
- Conversely, given any k edges which share no endpoints, simply put one unit of flow along each edge, and continue the flow to s and t. This will be a valid flow for the same reasons.
Hence, a maximum flow must correspond to a maximum matching, and vice versa. So if we had an algorithm to find maximum flows, we could use it to compute maximum matchings in bipartite graphs.
Committee assignment [00TQ]
- November 25, 2026
Consider the following scenario:
- There are a number of committees; each committee has a desired number of people.
- There is a set of people; each person has (1) a list of committees they are willing to be on, and (2) a maximum total number of committees they are willing to be on.
We can solve this by creating a flow network, as follows:
- There is a vertex for each person, a vertex for each committee, and special source and sink vertices s and t.
- We add an edge from s each each person, with capacity equal to the total number of committees that person is willing to be on.
- From each person, we add edges of capacity 1 to each committee they are willing to be on.
- From each committee, we add an edge to the sink t with capacity equal to the desired size of the committee.
Since valid flows correspond to valid assignments, it is possible to fill all the committees if and only if a maximum flow saturates all the edges going into t.
Escape route planning [00TR]
- November 25, 2026
As another example application for finding max flows, imagine trying to plan escape routes for evacuating a city. Formally, we model a city as a directed graph. Each vertex has a weight corresponding to the number of people who start there (for example, we might assign every vertex some number corresponding to population density; or if we are trying to model evacuation from large events we might just assign a few vertices some large number, etc.). Certain vertices are designated as "escapes" (which could correspond to shelters, or simply to vertices on the edge of the graph), each having a capacity corresponding to the number of people it can handle. Each edge also has a capacity corresponding to how many people it can handle. The goal is to see how many people we can get from their starting locations to an escape, and plan which routes they should use.
Once again, we can make this into a flow network as follows:
- Create a source vertex s, and add an edge from s to each vertex v with capacity equal to the number of people that start at v.
- Create a sink vertex t, and add an edge from each escape vertex to t with capacity equal to the capacity of the escape.
Other max flow applications [00TS]
- November 25, 2026
There are many other interesting applications of maximum flows, including:
- Baseball elimination: max flow can be used to compute which baseball teams can still make the playoffs, and which have been definitely eliminated.
- Image segmentation: max flow can be used to separate images into background and foreground.
- Airline scheduling: a generalization of max flow which includes lower bounds on flows can be used to figure out optimal ways to schedule flights and crews for an airline.
Attempt: greedy max flow [00S3]
- November 11, 2026
How should we design an algorithm to solve the maximum flow problem? Well, let’s first try a greedy strategy, which looks for an unsaturated path from s to t (that is, a path for which the flow along every edge is less than the edge’s capacity), increases (augments) the flow along that path as much as possible, and then repeats until no unsaturated path is left.
Algorithm Greedy Flow [00S4]
- November 11, 2026
Greedy flow counterexample [00S5]
- November 11, 2026
Unfortunately, this greedy flow algorithm does not work. We may get stuck in a “local optimum” where there are no more unsaturated paths, but we have not found the globally maximum flow. Here is a counterexample.
However, all is not lost! We can actually keep the basic outline of the greedy algorithm. We really just need to allow ourselves to undo or “push back” flow if we find somewhere better for it to go.
Residual networks [00SB]
- November 12, 2026
For a given network G and flow f, we define the residual network G_f. The residual network has the same vertices as G and essentially has two edges for each edge e = (u,v) in G: one from u to v with weight equal to the remaining capacity c(e) - f(e), and one “backwards” edge from v to u with weight equal to the flow flow f(e) along e. The backwards edge allows us to “retract” some of the flow along e. The only wrinkle is that we don’t include edges with zero capacity, so some edges of G only have one corresponding edge in G_f: those with zero flow (which have only a corresponding forward edge) or those at maximum capacity (which have only a corresponding backward edge). Formally:
Definition Residual network [00SC]
- November 12, 2026
Given a flow network G=(V,E) and a flow f on G, we define the residual network G_{f} as a directed, weighted graph G_{f}=(V,E_f), with E_f = \{ e \in E \mid c(e) - f(e) > 0 \} \cup \{ e^R \mid e \in E, f(e) > 0 \} (where e^R denotes the reverse of edge e) and we define the weights of edges in E_f by
- w(e)=c(e)-f(e), and
- w(e^{R}) = f(e).
The Ford-Fulkerson algorithm [00SD]
- November 12, 2026
We can now define the Ford-Fulkerson algorithm, which is similar to the greedy flow algorithm but uses the residual network instead of the original network to find augmenting paths. Every time an augmenting path traverses a "forwards" edge in the residual network, we add flow to the corresponding edge in G; when an augmenting path traverses a "backwards" edge, we subtract flow from the corresponding edge in G.
Algorithm Ford-Fulkerson [00SE]
- November 12, 2026
We take a moment to record a few observations/lemmas about this algorithm.
Lemma Augmenting preserves flow validity [00SF]
- November 12, 2026
Augmenting along an s-t path in the residual network always preserves the flow properties.
Proof.
- November 12, 2026
- If we augment along two consecutive "forwards" edges in G_f, we add the same amount of flow to both incoming and outgoing edges of their common vertex in G.
- If we augment along two consecutive "backwards" edges, we subtract the same amount of flow to both an incoming and outgoing edge in G.
- If we augment along a forwards edge followed by a backwards edge, we add flow to one incoming edge and subtract flow from another incoming edge. Likewise, if we augment along a backwards edge followed by a forwards edge, we add and subtract the same amount of flow from two outgoing edges.
In addition, because of the way weights are defined on edges in the residual network, we can never add flow beyond capacity, or reduce a flow below zero.
Lemma Augmenting increases flow value [00SG]
- November 12, 2026
Augmenting along an s-t path in the residual network always increases the value of the flow in G.
Proof.
- November 12, 2026
Lemma Ford-Fulkerson terminates [00SH]
- November 12, 2026
The Ford-Fulkerson algorithm terminates (the flow can’t keep getting bigger forever).
Proof.
- November 12, 2026
Runtime analysis [00SM]
- November 12, 2026
The Ford-Fulkerson algorithm can be implemented to run in O(CE) time, where C is the total capacity of outgoing edges from the source.
- At every iteration, the flow value must increase by at least 1. Hence C is an upper bound on the number of iterations of the while loop.
- Finding an augmenting path can be done in \Theta (V+E) using something like DFS. In fact, there's not much point running this algorithm on a disconnected graph, so we can assume E is \Omega (V). Hence this is just \Theta (E).
- Augmenting along the path P and updating the residual network appropriately can be carried out in \Theta (E) worst-case time (constant time per edge of P) with careful choices of data structures. (In practice we store the information about flow and about G_f in the same data structure; we also need to keep pointers from each "backwards" edge to the corresponding forwards edge in order to augment efficiently.)
★ Maximum flow algorithms in practice [00SL]
- November 12, 2026
Ford-Fulkerson is actually a kind of meta-algorithm: it specifies the method of repeatedly augmenting along s-t paths in the residual network (augmenting paths) but it doesn’t actually specify how to find augmenting paths. Without specifying how to find augmenting paths at all, we proved that Ford-Fulkerson will run in O(EC) time, where E is the number of edges and C is the total capacity leaving the source (or the total capacity entering the sink, whichever is smaller). But if we are more careful about how we find augmenting paths we can do better.
- The most straightforward way is to simply use a DFS from s to t in the residual network. This works fine but not particularly well; depending on the graph it can exhibit the worst case O(EC) behavior.
- We can use BFS in the residual network to find the shortest augmenting path on each iteration. This is called the Edmonds-Karp algorithm, and it can be shown (though the proof is outside the scope of this course) that it runs in O(VE^2)—in particular, the running time does not depend on the capacities. This algorithm works very well in practice, and often runs much faster than the worst case, behaving more like \Theta (E^{3/2}).
- We could use a variant of Dijkstra’s algorithm to find the maximum capacity augmenting path on each iteration. This seems like it would be a good idea, but in practice it is usually slower than Edmonds-Karp.
- Finally, there is a clever method, Dinitz’s Algorithm, which instead of finding just a single augmenting path each iteration, sends flow along multiple augmenting paths at once. (Note: it is often known as Dinic’s Algorithm, but this is due to a misspelling of the name of its inventor, Yefim Dinitz.) It works as follows:
- Do a BFS from s in the residual network and label every vertex with its level in the BFS tree.
- Now do a DFS from s in the residual network, only taking edges which go from level i to i+1; as we recurse through the graph, keep track of the available flow and the minimum residual capacity along the path to each point. Once we reach s we can unroll the recursion and update flow values with the minimum capacity seen along the path, and subtract the augmenting flow from the available flow. Instead of stopping, however, we keep going to try to augment along as many paths as we can. If we encounter a vertex from which it’s impossible to reach t, we mark it so we know not to visit it if we ever encounter it again.
There are many other approaches to finding maximum flows as well (preflow-push/push-relabel, simplex…), which can have even better asymptotic running times, work better on certain types of graph, or solve more complex max flow variants (max circulation, min-cost max flow, …), but for most practical max flow problems you will encounter, Edmonds-Karp or Dinitz should work just fine!
Max flow/min cut theorem [00SN]
- November 12, 2026
We now present one of the great duality results in computer science—that the maximum flow of a network is equivalent to the minimum cut of a network. Along the way, we will also show that f is a max flow if and only there are no augmenting paths in the residual network G_{f}, which proves the correctness of Ford-Fulkerson.
Definition s-t cut [00SO]
- November 16, 2026
An s-t cut in a flow network G = (V,E) is a partition of V into two sets (A,B) where s \in A and t \in B.
Definition Cut capacity [00SP]
- November 16, 2026
The capacity of an s-t cut, denoted c(A,B), is the total capacity of all edges crossing the cut. That is, c(A,B) = \sum _{e : A \to B} c(e). (The notation e : A \to B denotes any edge which goes from some vertex in A to some vertex in B.)
Definition Minimum cut [00SQ]
- November 16, 2026
Definition Net flow [00SR]
- November 16, 2026
Remark [00SS]
- November 16, 2026
If we imagine the vertices of A being “clumped together” around the source vertex, then it’s clear what should happen: there will be no flow coming in to A, and the flow going out will just be equal to the value of the flow. But A could be crazier—it could consist of a bunch of vertices scattered all through the graph. They don’t even have to be connected. So what can we say about the net flow in general?
Lemma Flow Value Lemma [00ST]
- November 16, 2026
Let f be any flow and let (A,B) be any s-t cut in a flow network G. Then the net flow of (A,B) with respect to f equals the value of f. That is, v(A,B) = v(f).
Proof.
- November 16, 2026
The remaining step that needs explanation is the central one that goes from \sum _{v \in A} (f^{\mathrm {out}}(v) - f^{\mathrm {in}}(v)) to \sum _{e : A \to B} f(e) - \sum _{e : B \to A} f(e). To see why this is true, consider all the edges with at least one endpoint in A.
- If an edge has both endpoints in A, its flow contributes twice to the first sum, once positively and once negatively, and the two cancel out. (Intuitively: moving stuff around within A does not affect its net exports.)
- Edges leaving A contribute positively to the sum.
- Edges entering A contribute negatively to the sum.
Lemma Bottleneck lemma [00SU]
- November 16, 2026
Let f be any flow and (A,B) be any s-t cut. Then the capacity of the cut is at least the value of the flow, that is, v(f) \leq c(A,B).
Proof.
- November 16, 2026
Remark
- November 16, 2026
From the proof we can see that v(f) = c(A,B) exactly when (1) there is no flow entering A and (2) every edge leaving A is saturated (that is, f(e) = c(e)).
Corollary Saturated cut = max flow + min cut [00T2]
- November 17, 2026
Given some flow f and s-t cut (A,B), if v(f) = c(A,B) then f is a max flow and (A,B) is a min cut.
Proof.
- November 17, 2026
Theorem Max flow/min cut [00T3]
- November 17, 2026
Let f be any flow on a flow network G. The following are equivalent:
- v(f) = c(A,B) for some cut (A,B).
- f is a max flow.
- There are no s-t paths in the residual network G_{f}.
Remark
- November 17, 2026
As an aside, theorems of this form ("the following are equivalent") do not come up as often in computer science, but they are a lot of fun. (We already saw one other similar example earlier.) How do we prove theorems of this form? If we think of each proposition as a vertex, and proving that P implies Q corresponds to adding a directed edge from P to Q, then our goal is to ensure that the resulting graph is strongly connected, so there is a path from any proposition to any other. Since implication is transitive, this shows that all the propositions are logically equivalent.
Proof.
- November 17, 2026
- 1 \Rightarrow 2 is just Saturated cut = max flow + min cut.
- 2 \Rightarrow 3 because Augmenting increases flow value: if there were an s-t path in G_{f}, then we could increase the flow along that path, so f would not be a max flow. (This is the contrapositive of 2 \Rightarrow 3.)
(3 \Rightarrow 1) is more interesting. Suppose there are no s-t paths in G_f; then we must somehow come up with a cut (A,B) whose capacity is equal to that of the flow! To this end, define an s-t cut (A,B) as follows:
- A = all nodes reachable from s in G_{f}.
- B = everything else.
Notice that
- s \in A (s is trivially reachable from itself).
- t \in B (t can’t be in A, since we assumed there are no s-t paths in G_{f}).
The Flow Value Lemma tells us that the value of the flow is equal to the net flow across the cut (A,B), that is, v(f) = v(A,B) = \sum _{e : A \to B} f(e) \;\; - \sum _{e : B \to A} f(e).
Note that each edge (u,v) leaving A must be filled to capacity, since otherwise there would be a forwards edge from u to v with the remaining capacity in G_f, but then by definition we would have v \in A since v would be reachable in G_f. Similarly, each edge entering A must have 0 flow since if it didn’t, there would be a backwards edge from v to u in G_f, and then u would be in A as well.
Hence, we have
Corollary Ford-Fulkerson is correct [00T4]
- November 17, 2026
The Ford-Fulkerson algorithm is correct.
Proof.
- November 17, 2026
Amortized analysis [00SV]
- November 17, 2026
Amortized analysis introduction and motivation [00SW]
- November 17, 2026
Binary counter incrementing [00SX]
- November 17, 2026
Consider the following problem.
Input: an array B[0\dots ] representing a binary number n. (Each B[i] is a single bit representing the coefficient of 2^i. Assume B is sufficiently large so we don’t have to worry about problems with overflow.)
Output: Increment the binary number, that is, modify B so that it represents the number n+1.
Algorithm Incrementing a binary counter [00SY]
- November 17, 2026
Here is an algorithm to solve the binary counter problem.
Binary counter increment analysis [00SZ]
- November 17, 2026
How long does this algorithm take?
- The best case is \Theta (1): if the last bit of n is 0 then all we have to do is flip it. The while loop never executes at all.
- The worst case is when n is of the form 2^k - 1, that is, all 1 bits, and to increment it we have to flip all the 1’s to 0s and then set the next 0 bit to 1. Since n requires \Theta (\lg n) bits to represent it, this means that incrementing n takes \Theta (\lg n) in the worst case.
Therefore, a sequence of n increment operations takes \Omega (n) time in the best case, and O(n \lg n) in the worst case. However, we don't typically do a bunch of random increment operations; more realistically, we start a counter at 0 and repeatedly increment up to n. We can observe that many such operations will be best cases, and that the worst case happens only infrequently. Can we say something more precise about how long it takes to perform a n increment operations (and thus how long a single increment operation takes on average)?
Amortized analysis in general [00T0]
- November 17, 2026
This is a common situation: we have some operation that we want to do repeatedly, and the operation does not always take the same amount of time. We can easily give an upper bound and a lower bound, but we want to be able to say something more precise about how long the entire sequence of operations will take. For this we turn to amortized analysis. The idea of “amortization” is to spread out big one-time costs more evenly (e.g. repaying a car loan or a mortgage in monthly installments).
Approaching increment cost via a table [00T1]
- November 17, 2026
The first step is almost always to just try small examples, play around, make a table, and notice patterns to come up with a guess. Let’s try it for incrementing a binary counter. We’ll make a table with the counter value n and the cumulative number of bit flips on the right-hand side. Remember we don’t need a formula for the number of bit flips (though it turns out in this case it is possible to come up with one!); we are just trying to figure out how fast it grows in relation to n.
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| flips | 1 | 2 | 1 | 3 | 1 | 2 | 1 | 4 | 1 | 2 | 1 | 3 | 1 | 2 | 1 | 5 | |
| total | 0 | 1 | 3 | 4 | 7 | 8 | 10 | 11 | 15 | 16 | 18 | 19 | 22 | 23 | 25 | 26 | 31 |
We notice some patterns: whenever n is a power of two, the total number of bit flips seems to be one less than the next power of two. In fact, in general it seems that the cumulative number of bit flips is never more than 2n. That is, we conjecture that T(n) < 2n for all n > 0. Based on this evidence, we conjecture that a sequence of n increment operations starting from 0 actually takes \Theta (n), the lower bound we derived from the best case, rather than the worst-case upper bound of \Theta (n \lg n). Intuitively, it seems like the “expensive” increment operations happen infrequently enough that they don’t add too much to the total—we can “average out” their cost over the whole sequence.
The average cost of a single increment operation is just the total cost, T(n), divided by the number of operations (n). If it's true that T(n) < 2n, then the average is T(n)/n < 2n/n = 2 = \Theta (1). In this case we say that a single increment operation takes \Theta (1) amortized time: each increment takes \Theta (1) “on average”, even though an individual increment operation could take longer.
So how can we actually prove this? There are (at least) three methods; we will cover two of them.
Direct calculation [00T5]
- November 18, 2026
Sometimes, we can actually compute a formula for the total T(n) of a sequence of n operations—or at least show that the total T(n) is bounded by some simple formula. Then we can calculate the amortized time for a single operation as T(n)/n.
As an example, let's try coming up with a formula for the total number of bit flips needed to increment a binary counter from 0 to n. We have T(n) = 1 + 2 + 1 + 3 + 1 + 2 + 1 + 4 + 1 + 2 + 1 + 3 + 1 + 2 + 1 + 5 + \dots Incidentally, this pattern is sometimes called the ruler function since it looks like a traditional ruler showing inches, half inches, quarter inches... with each subsequent marking being shorter:
It's not obvious how to come up with a formula for T(n), but a change of perspective is often helpful, such as rearranging the terms being added or slicing them a different way. In this case, if we draw the terms being added with dots, it looks like this:
Instead of adding up each column, we can think about adding by rows. The bottom row contains n dots, because the last bit flips with every single increment. The second-to-last row contains \lfloor n/2 \rfloor dots, because the second-to-last bit flips every other increment. The third-to-last row contains \lfloor n/4 \rfloor dots, and so on. Hence T(n) = n + \lfloor n/2 \rfloor + \lfloor n/4 \rfloor + \lfloor n/8 \rfloor + \dots This formula is exact, since at some point \lfloor n/2^k \rfloor becomes zero, for k > \lg n.We still don't know how to simplify this exactly, but we don't need to: remember that we are just trying to show that T(n) < 2n. So we can compute as follows:
Remark
- November 18, 2026
Note that we only claim T(n) \leq 2n in the above proof, not T(n) < 2n as conjectured, since this is still good enough to give us the result about increment taking \Theta (1) on average. In fact, we can replace the \leq in the proof with <, but it would require a slightly more nuanced argument about why removing the rounding makes the sum strictly larger.
Accounting Method [00T6]
- November 18, 2026
Imagine that each constant-time operation “costs” $1. The idea is to overcharge for some operations and “save up” the extra money, so that we have enough saved up to pay for expensive operations. In general, if we charge c \cdot f(n) for some operations and always have enough left over to pay for the other operations, then we can say that each operation takes O(f(n)) amortized time.
In this example, we imagine that flipping a bit costs $1. Let’s charge $2 every time we flip a bit from 0 to 1. $1 will pay for the flip itself, and the other $1 we imagine being saved next to the 1 bit. Later, when we need to flip the bit back to 0, we will have $1 sitting there which we can use to pay for the flip. 000 \overset {\text {\textdollar } 2}{\longrightarrow } 00\underset {\text {\textdollar }}{1} \overset {\text {\textdollar } 2}{\longrightarrow } 0\underset {\text {\textdollar }}{1} 0 \overset {\text {\textdollar } 2}{\longrightarrow } 0\underset {\text {\textdollar }}{1}\underset {\text {\textdollar }}{1} \overset {\text {\textdollar } 2}{\longrightarrow } \underset {\text {\textdollar }}{1} 00 Notice how every increment operation does exactly one 0 \to 1 flip, for which we pay $2. And it might do a bunch of 1 \to 0 flips, but we get to do those “for free” using the money we saved up from previous increments. All in all, if we pay $2 for each increment we always have enough money to pay for all the bit flips (without ever going negative). Therefore, we conclude that the amortized cost of a single increment operation is $2, that is, \Theta (1).
As a fun aside, this analysis actually shows us how to come up with a precise formula for the total number of bit flips needed to increment from 0 to n: after doing n increment operations, we have paid \text {\textdollar }2n, but not all of that \text {\textdollar } 2n has actually been used. There is $1 sitting next to each 1 bit, and the rest of the \text {\textdollar } 2n has been used to pay for bit flips. So the total number of bit flips needed to increment from 0 to n is exactly 2n - \#n where \#n is the number of 1 bits in the binary representation of n.
★ Amortized analysis example: another binary counter [00TC]
- November 21, 2026
Take the same binary counter incrementing example, but now suppose it costs 2^i to flip bit i. The worst case for a single increment operation is now \Theta (n), since if we have to flip all the bits it will cost 2^0 + 2^1 + 2^2 + \dots which is approximately equal to n. But once again, the total time to do n successive increment operations is actually less than \Theta (n^2). Let’s again make a table and look for patterns.
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| incr | 1 | 3 | 1 | 7 | 1 | 3 | 1 | 15 | 1 | 3 | 1 | 7 | 1 | 3 | 1 | 31 | |
| total | 0 | 1 | 4 | 5 | 12 | 13 | 16 | 17 | 32 | 33 | 36 | 37 | 44 | 45 | 48 | 49 | 80 |
Looking at just the powers of 2 might reveal a useful pattern: 2 \to 4, 4 \to 12, 8 \to 32, 16 \to 80. It looks like each power of 2 is being multiplied by successive integers (2 \times 2, 4 \times 3, 8 \times 4, 16 \times 5…)in particular 2^k is being multiplied by k+1. So we conjecture that the total cost to increment from 0 to n is no greater than n \times (\lg n + 1), which would mean that the amortized cost of each increment operation is \Theta (\lg n).
To show this, we can use the accounting method: every time we do an increment, just put $1 on every bit, whether we flip it or not. (We have to decide up front how many bits we are going to use.) Since bit i is flipped every 2^i increment operations, by the time we flip it we will have accumulated exactly enough money to pay for its cost of 2^i. Therefore, the amortized cost of a single increment is the amount we actually pay: we pay $1 for each bit and there are \Theta (\lg n) bits.
We could also use the direct calculation method. Note that bit i is flipped only once every 2^i increments, and flipping it costs 2^i. So each bit contributes a total cost that is at most the total number of increment operations. There are \lg n + 1 bits, and each contributes a cost of at most n, for a total of at most n (\lg n + 1).
Amortized analysis example: extensible arrays [00TD]
- November 21, 2026
Another example that should be familiar from Data Structures: extensible arrays (e.g. ArrayList in Java). As our cost model, suppose accessing or modifying an array entry costs 1, and allocating a new array and copying the contents of an old array into it costs n (the length of the old array). Every time we do an \mathsf {append} operation, it might cost \Theta (1) (if there is still enough space in the underlying array) or it might cost \Theta (n) if we have to allocate a bigger array, copy all the elements over from the old array, and then insert the new element. So we can definitely say that a sequence of n \mathsf {append} operations is \Omega (n) and O(n^2).
The question is, what strategy should we use for allocating a new array when we run out of space? This turns out to have a big impact on the amortized time of \mathsf {append}.
- Strategy 1: increase the size by some constant c. That is, when our array of size n becomes full, allocate a new array of size n + c and copy the contents of the old array into it.
- Strategy 2: double the size. That is, when our array of size n becomes full, allocate a new array of size 2n.
Let’s consider the amortized time for a single \mathsf {append} operation using these strategies.
Strategy 1: suppose we start with an array of size c. (The starting size of the array does not really change the analysis at all.) The first c \mathsf {append} operations will cost 1 each, and then the next will cost c + 1 (c to copy the now-full array of size c, and 1 more to insert the new element). Then there will be another c-1 operations that cost 1 each until the new array is full. The next will cost 2c + 1 (copy the full array of size 2c plus 1 to insert). And so on.
In general, if we do n successive \mathsf {append} operations, we will end up paying n for the actual inserts, plus c + 2c + 3c + 4c + \dots + \lfloor n/c \rfloor c for array allocations. This is c (1 + 2 + 3 + \dots + \lfloor n/c \rfloor ) = c \cdot \Theta ((n/c)^2) = \Theta (n^2). So the total cost for n successive \mathsf {append} operations is \Theta (n) + \Theta (n^2) = \Theta (n^2), and a single \mathsf {append} has an amortized cost of \Theta (n). In this case, the cost of the expensive operations ends up dominating, even though most of the calls to \mathsf {append} are just \Theta (1).
Intuitively, since c is fixed, as our array becomes large, we spend an increasingly large fraction of the time allocating and copying arrays, relatively speaking.
Strategy 2: suppose we start with an array of size 1. If we do a sequence of n \mathsf {append} operations, of course we will still pay n for the actual insertions; the question is how much we pay for array allocations. After the initial array becomes full (immediately), we pay 1 to allocate a new array of size 2 and copy the element over. When that becomes full, we pay 2 to allocate an array of size 4 and copy over the old elements. And so on. In total, we will pay 1 + 2 + 4 + 8 + \dots + 2^k, where 2^k is the biggest power of 2 which is less than n. But this sum is 2^{k+1} - 1 which is approximately 2n, that is, \Theta (n). So the total cost of n calls to \mathsf {append} is \Theta (n) + \Theta (n) = \Theta (n), and the amortized cost of a single \mathsf {append} is only \Theta (1).
We can also prove this using the accounting method. Charge $3 for each \mathsf {append}. $1 goes to paying for the actual array insertion; the other $2 is saved along with the inserted element. Each time the array becomes full, it will look something like this:
1 3 19 -5 \underset {\text {\textdollar }\text {\textdollar }}{6} \underset {\text {\textdollar }\text {\textdollar }}{8} \underset {\text {\textdollar }\text {\textdollar }}{21} \underset {\text {\textdollar }\text {\textdollar }}{0} Since the array capacity was doubled the last time it was resized, for each element already in the array there will be a newly inserted element with $2 stored next to it. Therefore the total amount of money available is equal to the number of elements in the array, and we can pay to allocate a new array and copy all the elements over.
Thus, the amortized cost of a single \mathsf {append} operation is $3, that is, \Theta (1).
Binomial heaps [00TE]
- November 21, 2026
Binomial heap motivation [00TF]
- November 21, 2026
Recall the binary heap data structure—a complete binary tree where the value at each node is less than the values at both its children. This lets us implement priority queues with \Theta (\lg n)-time insert, remove-minimum, and change-key operations.
Consider the merge operation: given two priority queues, merge them into a single combined priority queue. This is a natural and useful operation in many applications. Unfortunately, binary heaps do not support this operation at all. The best one can do is to just list all the elements in the two heaps and then build a new heap out of the elements; this takes linear time. Can we do better?
Definition Binomial tree [00TG]
- November 21, 2026
Lemma Binomial tree size [00TH]
- November 21, 2026
A binomial tree of order n has 2^n nodes.
Proof.
- November 21, 2026
Remark Binomial trees and binomial coefficients [00TI]
- November 21, 2026
Binomial trees are called binomial since a binomial tree of order n has \binom n k nodes at depth k. This can also be proved by induction, using some facts about binomial coefficients (just think about adding a row of Pascal’s triangle shifted against itself to get the next row).
Lemma Gluing binomial trees [00TJ]
- November 21, 2026
We can make a binomial tree of order n out of two binomial trees of order n-1, by attaching one of the trees as the rightmost child of the other tree’s root node. This is apparent from the pictures above and from the definition.
Definition Binomial heap [00TK]
- November 21, 2026
A binomial heap is a list of binomial trees such that:
- Each binomial tree satisfies the heap property (the value stored at each node is smaller than all its children)
- There is at most one binomial tree of any given order.
Below is an example of a valid binomial heap.
Binomial heaps and binary numbers [00TL]
- November 21, 2026
We usually keep the list of binomial trees sorted from smallest to biggest order, stored using a linked list. (I will draw them sorted from right to left.) Notice that a binomial heap acts a lot like a binary number: since binomial trees have sizes that are powers of two, and a binomial heap has at most one tree of any given order, it is not hard to see that a binomial heap with n total elements has a binomial tree of order k if and only if the 2^k bit of the binary representation of n is a 1. For example, the heap illustrated above has 13 nodes, 13_2 = 1101, and indeed the heap has one tree of order 0 (size 1), one of order 2 (size 4), and one of order 3 (size 8). This also means a binomial heap of size n contains O(\lg n) trees, from order 0 up through order \lfloor \lg n \rfloor .
Merging binomial trees [00TM]
- November 21, 2026
To merge two binomial trees of order k with the heap property into a single binomial tree of order k+1 that also has the heap property, just see which one has the bigger root, and make it the leftmost child of the smaller root. This takes \Theta (1) time.
Merging binomial heaps [00TN]
- November 21, 2026
To merge two binomial heaps A and B, we can do what amounts to addition of binary numbers. Iterate through them in parallel, from order 0 up. For each order k we have possibly a binomial tree of order k from A, possibly a tree of order k from B, and we also may possibly have a carry tree of order k, just like we can carry a 1 bit when adding binary numbers. (When we start out at k = 0 we have no carry tree.)
- If there are no trees of order k, the output has no trees of order k. (0 + 0 = 0.)
- If there is only one tree of order k, just copy it to the output. (0 + 1 = 1.)
- If there are two trees of order k, merge them into a single tree of order k+1 and make it the carry tree for the next iteration; the output has no trees of order k. (1 + 1 = 10, so output 0 and carry the 1.)
- If there are three trees of order k, copy one of them to the output, and merge the other two into an order-(k+1) carry tree. (1 + 1 + 1 = 11: output 1 and carry 1.)
Each iteration of the above algorithm takes constant time: we may have to merge two trees but that takes constant time. So merging two binomial heaps of size n can be done in \Theta (\lg n) time, since we do \Theta (1) work for each order from 0 up to \lfloor \lg n \rfloor .
Other operations on binomial heaps [00TO]
- November 21, 2026
Now, let’s see how we can implement the other priority queue methods as well:
- \mathsf {Insert}: to insert a new element x into a binomial heap H, make x into a size-1 binomial heap (containing a single order-0 binomial tree) and then merge it with H. This is just like incrementing a binary counter! So although it is O(\lg n) in the worst case, it takes \Theta (1) amortized time. (This is even better than a standard binary-tree based heap, which always takes \Theta (\lg n) to insert!)
- \mathsf {Delete}-\mathsf {min}: iterate through the roots of all the trees to find the smallest in \Theta (\lg n) time (the smallest element in the entire heap is guaranteed to be one of the roots). Removing it leaves its children, which are binomial trees of order k-1, k-2, …, 0: a binomial heap! Just merge this remaining binomial heap with the rest of the heap in \Theta (\lg n) time. So overall delete-min takes \Theta (\lg n). (Note we can also keep track of the minimum root so that finding the minimum can be \Theta (1), even though removing it still takes \Theta (\lg n).)
- \mathsf {Change}-\mathsf {key}: just bubble the key up or down within its binomial tree until it is at the right spot. This takes O(\lg n).
★ The Potential Method [00TT]
- November 25, 2026
Motivation [00TU]
- November 25, 2026
There is one more method we can use to prove amortized time bounds, called the potential method, which comes from an analogy with physics. The idea is to think of a data structure as having some “potential energy”. Operations on the data structure will sometimes increase the potential energy (storing up some extra energy that can be used later) and sometimes decrease it (releasing some of the stored energy). The amortized cost of an operation is the actual cost of the operation plus the change in energy. The change in energy can be positive (in which case the amortized cost is more than the actual cost, and some energy is stored for later) or negative (in which case the amortized cost is less than the actual cost, using up some of the stored energy to pay for the difference).
The Potential Method, formally [00TV]
- November 25, 2026
Consider a sequence of operations on a data structure, and let D_i denote the state of the data structure after the ith operation, and \Phi _i the potential energy of D_i. Then the amortized cost of the ith operation (which turned D_{i-1} into D_i) is defined as a_i = c_i + \Phi _i - \Phi _{i-1} where c_i is the actual cost of the operation. Therefore the amortized cost of the sequence of operations is \sum _{i=1}^n a_i = \sum _{i=1}^n (c_i + \Phi _i - \Phi _{i-1}) =
\left ( \sum _{i=1}^n c_i \right ) + \Phi _n - \Phi _0. We need the total amortized cost to be an upper bound on the actual cost, and we can see this will happen as long as \Phi _n - \Phi _0 \geq 0, which motivates the following definition:
\Phi is valid if \Phi _i - \Phi _0 \geq 0 for all i.Definition Valid potential function [00TW]
Remark Potential method generalizes accounting method [00TX]
- November 25, 2026
Note that this can be seen as a generalization of the accounting method: the amount of “extra money” stored in a data structure can be thought of as “potential energy”. But the potential method makes it more clear that the energy does not have to be an integer, nor does it have to be “stored” anywhere in particular. In some cases this leads to an easier analysis even though in theory we could do the analysis using the accounting method (with weird fractional amounts of money stored in a “bank account”).
★ Splay trees [00TY]
- November 25, 2026
Splay tree motivation [00TZ]
- November 25, 2026
As a fascinating application of the potential method we will study splay trees, a sort of “self-balancing” variant of binary search trees. Recall that binary search trees give us \Theta (\lg n) insert, lookup, and delete for ordered data, as long as the trees remain balanced. But if the tree becomes unbalanced these turn into O(n) instead. In some applications it does not matter; if a binary search tree is built randomly it is very likely to be balanced. However, in many applications the data may have characteristics that lead to an unbalanced tree (for example, the data may be already sorted or close to sorted, in which case inserting it sequentially into a naive BST creates an unbalanced tree). There are various ways to solve this problem. What most people think of are sophisticated BST variants, such as red-black trees and AVL trees, which work by storing extra information in the trees and then using this extra information to make sure the trees remain balanced. Practically speaking, these are some of the best BST implementations, but they are complex, and require reimplementing all the BST methods to ensure that the extra information is kept up-to-date and that the tree is rebalanced as necessary.
Splay trees, intuitively [00U0]
- November 25, 2026
Splay trees are an intriguing alternative: a splay tree is just a normal binary search tree, with no extra information stored anywhere. The twist is that we implement an extra splay operation which works to make the tree a little more balanced, and we use this operation in conjunction with other operations such as lookup and insert, in such a way that the tree tends to stay balanced.
In particular, the \mathsf {Splay} operation works by bringing a particular element to the root of the BST (while keeping all the same elements in the tree and preserving the BST properties). It uses a particular algorithm that we will explore shortly. However, given such an operation that brings a chosen node to the root of a BST, let’s see how we update the other BST operations to use it:
- \mathsf {Insert}: Whenever we insert a new value into the splay tree (which works just like normal BST insertion), we then splay the newly inserted element to the root.
- \mathsf {Lookup}: Similarly, lookup works just like in a normal BST; but after doing a lookup we splay the looked up element (or the closest element, in the case that the element being searched for is not in the tree).
- \mathsf {Join}: If all the elements in T_1 are less than all the elements in T_2, we can join them into a single BST by first splaying the largest element in T_1 to the root, then adding T_2 as its right child (if the largest element is at the root of a BST, by definition it has no right child, so there is a clear space to add T_2).
- \mathsf {Split}: To split a BST into two BSTs which contain all the elements less and greater than a particular target element, respectively, splay the target element to the root and then return its two children.
- \mathsf {Delete}: Splay the item to be deleted to the root, then \mathsf {join} the two subtrees. (This is only a minor point, but notice how much nicer this is than the usual BST delete implementation!)
The splay operation [00U1]
- November 25, 2026
Let’s see how \mathsf {Splay} actually works. We find the element x in the tree and then keep moving it up the tree until it reaches the root, according to the following three rules. In general we will use p to denote the parent of x and g to denote its grandparent. There are three general rules we apply depending on where x is in the tree.
ZIG [00UH]
- November 25, 2026
If x is the child of the root of the whole tree, then just do one rotation to move it to the root.
A, B, and C denote arbitrary subtrees. We don’t do anything to them at all, so the rotation takes constant time; we just need to update a few references. In the diagram, x is the left child of the root, so we rotate right, but there is also a second entirely symmetric case when x is the right child of the root and we rotate left.
Note how doing a rotation moves x up while preserving the binary search tree properties: all the elements in the subtree A are still to the left of x; all the ements in B remain in between x and p; and C remains to the right of p.
ZIG-ZIG [00UI]
- November 25, 2026
If x and p are either both left children or both right children, then do two successive rotations: first rotate around g \to p then around p \to x.
Some things to note:
- This rule applies anywhere in the tree, unlike ZIG which only applies when x is at a depth of 1. After applying ZIG-ZIG, x has moved two levels closer to the root.
- Like ZIG, this takes constant time, since we just do two rotations.
- Again, in the picture x and p are illustrated as both being left children, but there is an analogous symmetric case when x and p are both right children.
ZIG-ZAG [00UJ]
- November 25, 2026
Splay tree examples [00U2]
- November 25, 2026
Let’s start with some interactive examples to see how splay trees work in practice, and to gain some intuition for what we are trying to prove. For example, if we start with the tree on the left below, the next tree shows what we get if we splay 5 to the root; the tree after that shows what we would get if instead splay 4 to the root (starting from the tree on the left again); and so on. You can see that as we splay an element from deep in the tree, the other elements tend to “clump up” in twos due to the way we iterate the ZIG-ZIG rule.
And here is what happens when we iterate the ZIG-ZAG rule: starting from the tree on the left, splaying different elements results in the trees on the right:
In this case you can see that zigzags tend to get “unzipped” into two subtrees, one with the small nodes and one with the large nodes.We think of unbalanced trees as being “tense”/having a high potential energy; the splay operation tends to “relax” them, i.e. use some of the stored potential energy to do its work and then leave the tree in a lower-energy state. Doing lots of random splay operations tends to result in a balanced-ish tree. For example, if we start with a (very unbalanced) linear chain of 100 nodes numbered 0 to 99, and do 500 random splay operations, here is (one possible) result:
In fact, it turns out this still works even if the splay operations aren’t random: even if we have an evil adversary who is trying to choose splay operations which are as bad as possible for us, the tree will still tend towards balance! Intuitively, splaying an item that is already near the top of the tree doesn’t take very long; on the other hand, splaying an item that is deep in the tree takes a while but tends to make the rest of the tree more balanced. So the evil adversary can’t win.
Splay tree analysis [00U3]
- November 25, 2026
Theorem Amortized time for splay [00U4]
- November 25, 2026
The \mathsf {Splay} operation takes amortized \Theta (\lg n) time.
Remark Splay bounds other BST operations [00U5]
- November 25, 2026
We note first that this implies all the other methods (in particular \mathsf {Insert}, \mathsf {Lookup}, \mathsf {Delete}) will take amortized \Theta (\lg n) time as well. For \mathsf {Insert} and \mathsf {Lookup}, this is because they have exactly the same cost as splaying: when we lookup or insert, we travel down the tree, paying a cost proportional to the depth of the node we find or insert; then splaying that node to the root has exactly the same cost, since we travel back up exactly the same path, doing one rotation per level of depth. For \mathsf {Delete}, this is simply because it works by doing two \mathsf {Splay} operations.
Splay runtime proof [00U6]
- November 25, 2026
To prove that \mathsf {Splay} takes \Theta (\lg n) amortized time, we will use the potential method.
Definition Subtree size [00U7]
- November 25, 2026
If r is some node in a binary search tree, let S(r) be the size of the subtree rooted at r, that is, the number of nodes which have r as their ancestor (including r itself).
Definition Rank [00U8]
- November 25, 2026
The rank of a node r is defined by R(r) = \log _2(S(r)).
Definition Potential function = rank sum [00U9]
- November 25, 2026
Finally, let \Phi (T) be the sum of the ranks of all the nodes in the tree, that is, \Phi = \sum _{r \in T} R(r).
Rank sum examples [00UA]
- November 25, 2026
Note this is kind of weird and definitely not an integer! So thinking of this in terms of money would probably not work very well. For example, consider this tree:
Its three leaves all have size 1 and hence rank 0 (since \log _2 1 = 0); the internal node has size 3, and the root has size 5, so \Phi for this tree is \log _2 3 + \log _2 5. On the other hand, this tree: has a \Phi value of \log _2 5 + \log _2 4 + \log _2 3 + \log _2 2 + \log _2 1 = 3 + \log _2 5 + \log _2 3. In general, \Phi will be higher for more unbalanced trees.Remark Rank sum is a valid potential function [00UB]
- November 25, 2026
We note that \Phi is a valid potential function: \Phi for an empty tree is 0, and by definition it is clearly always positive. So the amortized time for an operation, that is, the sum of the actual cost and the change in potential, a = c + \Delta \Phi , will be a valid upper bound on the average cost of a single operation.
Before starting in on the proof proper, we will need a couple observations and lemmas about properties of the \lg (log base 2) function.
Observation \lg is increasing [00UC]
- November 25, 2026
\lg is an increasing function. So, if S(x) > S(y) then R(x) > R(y). In particular this means that R(x) > R(y) whenever x is an ancestor of y.
Lemma Maximum of \lg x + \lg (1 - x) [00UD]
- November 25, 2026
On the interval 0 < x < 1, the function \lg x + \lg (1-x) attains a maximum value of -2 (namely, when x = 1/2).
Proof.
- November 25, 2026
Remark [00UE]
- November 25, 2026
To get a more intuitive idea of why this is true, recall what the graph of \lg x looks like on the interval 0 < x < 1: it lies below the x-axis, passing through the points (1/2, -1) and (1,0), with a vertical asymptote as it diverges to -\infty as x \to 0. We are adding up the \lg of two values which are symmetric about the point x = 1/2. If we pick x = 1-x = 1/2 then the sum is -2. As we move the two points farther away from each other, the one moving left moves much faster in the negative y direction than the one moving to the right moves in the positive y direction, so the sum gets more negative.
Notation for node ranks [00UF]
- November 25, 2026
We want to talk about the rank of nodes before and after applying the splay rules. In general, for a node x we will use R(x) to refer to the rank of x before applying a rule, and R'(x) to refer to its new rank after applying the rule.
Important note: to understand the following proofs you really have to be looking at the pictures for the different splay rules!
Lemma Amortized cost of ZIG [00UG]
- November 25, 2026
The amortized cost of a ZIG operation is \leq 3(R'(x) - R(x)) + 1.
The amortized cost is defined as the actual cost plus the change in potential. In this case the actual cost of ZIG is 1 rotation. As for the change in potential, the ranks of x and p may change, but note that the ranks of all nodes in the subtrees A, B, and C do not change. Note also that the old rank of p is the same as the new rank of x (since p used to be the root of the whole tree, but afterwards x is, so the new x has the same number of nodes under it as the old p did). So the amortized cost is
Lemma ZIG-ZIG bound [00UK]
- November 25, 2026
In the context of the ZIG-ZIG operation, 2 \leq 2R'(x) - R(x) - R'(g).
Proof.
- November 25, 2026
For the final step, note that S(x) + S'(g) \leq S'(x) (since the original tree rooted at x and the new tree rooted at g are completely disjoint, and all the elements of both have x as an ancestor in the new tree), so \frac {S(x)}{S'(x)} + \frac {S'(g)}{S'(x)} = \frac {S(x) + S'(g)}{S'(x)} \leq 1. Therefore, the bound of -2 follows from the previous lemma.
The lemma as stated now follows by negating both sides of the inequality (and flipping the inequality appropriately).
Lemma Amortized cost of ZIG-ZIG [00UL]
- November 25, 2026
The amortized cost of a ZIG-ZIG operation is \leq 3(R'(x) - R(x)).
Proof.
- November 25, 2026
Lemma Amortized cost of ZIG-ZAG [00UM]
- November 25, 2026
The amortized cost of a ZIG-ZAG operation is \leq 3(R'(x) - R(x)).
Proof.
- November 25, 2026
Main proof for splay runtime [00UN]
- November 25, 2026
Now we have finally built the tools we need to prove the original theorem:
Theorem Amortized time for splay [00U4]
- November 25, 2026
The \mathsf {Splay} operation takes amortized \Theta (\lg n) time.
Proof.
- November 25, 2026
The amortized cost of a \mathsf {Splay} operation is the sum of the amortized costs of each of the rule applications as x makes its way up the tree; we have shown that each of these costs at most 3(R'(x) - R(x)), except possibly one final ZIG application which takes at most 1 + 3(R'(x) - R(x)). Note that in each case, the R'(x) from one step becomes the R(x) for the next step, and so the sum telescopes, with all of the intermediate R values cancelling, leaving at most 3(R(t) - R(x_0)) + 1, where t denotes the root of the entire tree (where x ultimately ends up) and x_0 denotes the starting location for x. The size of the tree t is of course n, so R(t) = \lg n. Also, in the worst case, x had to start all the way down at a leaf, which has R(x_0) = \lg 1 = 0. Therefore the amortized cost is bounded by 3\log _2 n + 1, which is O(\log n). Of course, it is clear that the cost has to be at least \Omega (\log n) as well, since the height of a tree of size n is at least \lg n. Therefore \mathsf {Splay} takes amortized \Theta (\lg n) time.
Intractability [00UO]
- November 30, 2026
Introduction to intractability [00UP]
- November 30, 2026
This week we will study the limits of computation, from an algorithmic perspective. What problems can computers solve, and what problems can’t they solve? Which problems can be solved efficiently and which can’t?
So far this semester, we typically pose some problem, think of a brute force solution, and then learn about some clever way to solve the problem much faster than brute force. At this point you might think that all problems are like this. But of course there is a lot of selection bias going on: I have chosen to tell you about problems which have nice solutions! In fact, there are quite a few problems—real-world problems that people actually care about—which do not (as far as we know) have nice, efficient solutions.
Independent sets and vertex covers [00UQ]
- November 30, 2026
Let's start by examining two problems which are important in practice but turn out not to have efficient solutions (as far as we know).
The independent set problem [00V1]
- November 30, 2026
Definition Independent set [00UR]
- November 30, 2026
An independent set in an undirected graph G = (V,E) is a subset of vertices S \subseteq V such that no two vertices in S are adjacent.
Example Independent sets [00US]
- November 30, 2026
Remark For independent sets, bigger = harder [00UT]
- November 30, 2026
The empty set \varnothing always counts as an independent set in any graph. Intuitively, making small independent sets is easy, but making bigger ones is more difficult: the more vertices we add, the harder it is to avoid picking a vertex which is adjacent to an existing one. This leads to the following interesting question.
Problem IND-SET-OPT [00UU]
- November 30, 2026
Given an undirected graph G, what is the maximum possible size of an independent set in G?
It will also be convenient to reformulate this as a problem with a yes-or-no answer, called a decision problem.
Definition Decision problem [00VL]
- December 2, 2026
A decision problem is a problem which, for any input, expects a yes-or-no answer.
Problem IND-SET [00UV]
- November 30, 2026
Given an undirected graph G and a natural number k, does there exist an independent set in G of size k or greater?
Remark IND-SET vs IND-SET-OPT [00UW]
- November 30, 2026
If we had an algorithm to solve IND-SET-OPT, we could obviously use it to solve IND-SET: given G and k, we ask our IND-SET-OPT algorithm for the size of the largest independent set and then check whether it is greater than or equal to k. Conversely, and slightly less obviously, if we had an algorithm to solve IND-SET, we could use it to solve IND-SET-OPT with only an extra factor of \Theta (\lg V): just use binary search to repeatedly ask the IND-SET algorithm about different sizes until "zeroing in" on the unique maximum size.
Something similar often happens with many problems: there is an "optimization version" which returns a best answer, and there is also a "decision version" which takes an extra parameter and decides whether the best answer is better than the given parameter or not. Since decision problems are simpler, and we can usually solve the optimization problem by doing binary search with the decision problem, we sometimes restrict ourselves to considering only decision problems.
Remark Independent sets in practice [00UZ]
- November 30, 2026
It's not too hard to think of reasons why people might concretely care about this problem. For example, imagine that each edge in a graph represents a conflict. Perhaps the vertices are tasks and there is an edge between two tasks if they cannot be done at the same time (because they both require the same resource, for example). Then an independent set represents a set of tasks that can all successfully be done simultaneously, and a maximum independent set is the largest possible such set of tasks.
Solving IND-SET-OPT by brute force [00V0]
- November 30, 2026
What would be a brute force algorithm to solve IND-SET-OPT (or IND-SET)? Just list every possible subset of V—there are 2^V such subsets—test whether each one is independent (by iterating through every possible pair of vertices), and keep track of the largest. Naïvely, this takes something like \Theta (2^V V^2). We can probably reduce this to \Theta (2^V) if we are clever, and perhaps even something like \Theta (2^{V/2}) if we are extremely clever—but astonishingly, we do not know of any fundamentally better algorithms! All the algorithms we know of have some kind of exponential running time, that is, V shows up in an exponent.
The vertex cover problem [00V2]
- November 30, 2026
Definition Vertex cover [00V3]
- November 30, 2026
A vertex cover in an undirected graph G = (V,E) is a subset of vertices S \subseteq V such that every edge has at least one endpoint in S.
Remark Museum guards [00V5]
- November 30, 2026
Intuitively, think of each edge as a straight hallway; then we want to hire some guards to put at the vertices, where each guard can "see" the edges adjacent to their vertex. A vertex cover is then a set of vertices where we can place guards such that every edge is guarded. Obviously in this case, it is more difficult to make a small vertex cover.
Problem VERTEX-COVER [00VY]
- November 30, 2026
Given an undirected graph G and a natural number k, does there exist a vertex cover in G of size k or less?
Theorem Independent set \iff vertex cover [00V6]
- November 30, 2026
For any undirected graph G, S \subseteq V is an independent set if and only if \overline {S} is a vertex cover. (Here \overline {S} = V \setminus S is the set complement of S, i.e. the set of vertices in V which are not in S.)
Proof.
- November 30, 2026
Subproof. Independent set \iff vertex cover ›
- November 30, 2026
Subproof. Independent set \iff vertex cover ›
- November 30, 2026
Corollary Maximum independent set \iff minimum vertex cover [00V7]
- November 30, 2026
S is a maximum independent set in G if and only if \overline {S} is a minimum vertex cover.
Proof.
- November 30, 2026
Satisfiability [00UX]
- November 30, 2026
Suppose we are given a set X = \{x_1, \dots , x_n\} of Boolean variables.
Definition Term [00V8]
- November 30, 2026
A term is either a variable x_i, or the logical negation of a variable, which we write \overline {x_i} (the negation of x_i is also often written \neg x_i).
Example Terms [00V9]
- November 30, 2026
For example, x_1 is a term, as is \overline {x_3}.
Definition Clause [00VA]
- November 30, 2026
A clause is a disjunction of one or more terms, t_1 \lor \dots \lor t_l.
Example Clauses [00VB]
- November 30, 2026
For example, x_1 \lor \overline {x_3} \lor x_4 is a clause. (Note there’s nothing in the definition precluding repeated variables like x_1 \lor x_1 \lor x_1 \lor x_3, but such repetition does not add anything from a logical point of view, so we usually think of the variables as being distinct.)
Definition Truth assignment [00VC]
- November 30, 2026
A truth assignment is a function X \to \{\mathsf {T},\mathsf {F}\} assigning a value of true or false to each variable x_i.
Definition Clause satisfaction [00VD]
- November 30, 2026
A truth assignment satisfies a clause C if it causes C to evaluate to true (under the usual rules of Boolean logic).
Example Clause satisfaction [00VE]
- November 30, 2026
For example, \{x_1 \mapsto \mathsf {T}, x_2 \mapsto \mathsf {F}, x_3 \mapsto \mathsf {F}, x_4 \mapsto \mathsf {F} \} satisfies x_1 \lor \overline {x_3} \lor x_4, but \{x_1 \mapsto \mathsf {F}, x_2 \mapsto \mathsf {F}, x_3 \mapsto \mathsf {T}, x_4 \mapsto \mathsf {F} \} does not. Note that it is always possible to come up with a satisfying truth assignment for any clause: just pick one of the terms and make it true.
Definition Satisfiability [00VF]
- November 30, 2026
A truth assignment v : X \to \{\mathsf {T},\mathsf {F}\} satisfies a collection of clauses C_1, \dots , C_k if it satisfies all of them (that is, it satisfies C_1 \land C_2 \land \dots \land C_k). We say that v is a satisfying assignment for \{C_1, \dots , C_k\}. When a collection of clauses has some satisfying assignment, we say it is satisfiable.
Example Satisfiable and unsatisfiable clause sets [00VG]
- November 30, 2026
For example, (x_1 \lor \overline {x_2}), (\overline {x_1} \lor \overline {x_3}), (x_2 \lor \overline {x_3}) is satisfiable: just set all x_i to \mathsf {F}. (This is not the only possible satisfying assignment.)
On the other hand, as you can verify, x_1, (x_3 \lor \overline {x_1}), (\overline {x_3} \lor \overline {x_1}) is not satisfiable: there is no way to assign truth values to the x_i which will simultaneously satisfy all the clauses.
Given these definitions, we can state the following problems:
Problem SAT [00VH]
- November 30, 2026
Satisfiability (SAT): Given clauses C_1, \dots , C_k over the variables X = \{x_1, \dots , x_n\}, is the collection of clauses satisfiable?
Here is another variant of SAT which seems like it might be easier (though as we will see, it is not):
Problem 3-SAT [00VI]
- November 30, 2026
3-SAT: Given a collection of clauses C_1, \dots , C_k each containing exactly three variables, is it satisfiable?
Solving SAT by brute force [00VJ]
- November 30, 2026
A brute-force algorithm for SAT (or 3-SAT) is to just try every possible truth assignment and check if any are satisfying. But if there are n variables, then there are 2^n possible truth assignments, so this brute force algorithm takes \Omega (2^n). Once again, it turns out that we do not know any fundamentally faster algorithms, although in practice there are "SAT solvers" which are vastly more efficient on real, practical problems than one might expect, even though there still exist worst-case inputs which would make them take exponential time.
\mathcal {P} and \mathcal {NP} [00VK]
- December 2, 2026
Motivation [00VM]
- December 2, 2026
Often, problems which seem hard to solve can nonetheless be easy to verify if we are handed a (potential) solution. For example, consider the IND-SET problem. We don’t yet know how hard it is to solve, but if someone hands you a set which they claim is an independent set of size \leq k, it is easy to verify whether it has the desired size and is, in fact, an independent set—just check each pair of vertices in the set to see whether they are connected by an edge. 3-SAT is similar: if someone hands you a variable assignment, all you have to do is plug it in and evaluate the clauses to see whether they are all satisfied.
Let’s be a bit more formal. We will suppose that the input to a problem is encoded as a binary string s. Formally, the “size” of the input will now be the number of bits, n = |s|. We will also identify a decision problem D with the set of all inputs s for which the answer should be “yes”. The problem then boils down to deciding whether a given bitstring s is contained in D or not. (This is another reason why studying decision problems is particularly nice.)
Definition Solve [00VN]
- December 2, 2026
An algorithm A solves a decision problem D if for all binary strings s, A(s) = \mathsf {T} iff s \in D. (Remember that we are identifying decision problems with the set of inputs for which the answer is \mathsf {T}.)
(Really, to be completely formal, we would need to identify an “algorithm” with some concrete model of computation, typically a Turing machine; but we will leave that level of formality to a Theory of Computation course.)
The class \mathcal {P} [00VS]
- December 2, 2026
Definition Polynomial time [00VO]
- December 2, 2026
If there is a polynomial p(n) such that A(s) always terminates in at most p(|s|) steps, we say A is a polynomial-time algorithm.
Definition \mathcal {P} [00VP]
- December 2, 2026
We define \mathcal {P} as the set of decision problems D solvable in polynomial time. That is, D \in \mathcal {P} if there exists some polynomial-time algorithm A which solves D.
Remark \mathcal {P} is problems [00VR]
- December 2, 2026
Note that \mathcal {P} is a set of problems, not a set of algorithms; it is the set of all problems which can be solved by some polynomial-time algorithm. For example, it does not make sense to say that Dijkstra's Algorithm is in \mathcal {P}; but it does make sense to say that the \mathsf {SHORTEST}-\mathsf {PATH} problem is in \mathcal {P}, since it can be solved by Dijkstra's Algorithm (which, as we know, is a polynomial-time algorithm).
Remark Why \mathcal {P}? [00VQ]
- December 2, 2026
Why focus on \mathcal {P}? As mentioned previously, we typically take polynomial-time as our definition of "feasible". There is both a theoretical and a practical reason for this. The theoretical reason is that the set of polynomials is closed under many natural operations. For example, if p(n) and q(n) are polynomials, then p(n) + q(n), p(n)q(n), and even p(q(n)) are all polynomials as well. If we have two algorithms which take time p(n) and q(n) respectively, then p(n) + q(n) represents the time to run the two algorithms in sequence; p(n)q(n) represents the time to run one nested inside the other; and even p(q(n)) corresponds to a natural operation on algorithms which we will encounter shortly. So if we focus on algorithms in \mathcal {P}, we can combine them in many natural ways and still remain in \mathcal {P}.
This would be a bad reason if it were only theoretically nice but did not correspond to reality very well. However, polynomial time corresponds well to what is feasible in practice. Most real polynomial-time algorithms have relatively small exponents; the biggest power I have ever seen in an algorithm which is actually used in practice is n^6. And there are many cases where a small tweak is all that separates a problem from being solvable in something like \Theta (n^2) time to requiring \Theta (2^n) time. That is, problems don't "degrade gracefully" from feasible to infeasible; there often seems to be a sharp divide where problems suddenly jump from having a nice, efficient, polynomial-time solution to having only exponential-time solutions.
The class \mathcal {NP} [00VT]
- December 2, 2026
Motivation [00VU]
- December 2, 2026
Now let’s formally define what it means to be able to verify the solution to a decision problem. The idea is that we need some sort of extra information to verify a positive answer to a decision problem. For example, given some large graph, if someone were to claim that there was an independent set of size \geq 20, you would challenge them to prove it to you by showing you the independent set. Given an actual set of vertices, it would be easy for you to check that the set has size \geq 20 and also that no two vertices in the set have an edge between them. Conversely, if there is no independent set of that size, then no one is going to be able to fool you by giving you some weird set of vertices. The extra information required to verify a solution is called a certificate.
Definition Polynomial-time certifier [00VV]
- December 2, 2026
An algorithm B is a polynomial-time certifier for a decision problem D if:
- B is a polynomial-time algorithm taking some inputs s and t
- There is a polynomial p such that for all bitstrings s, we have s \in D if and only if there is some bitstring t (called a certificate) with |t| \leq p(|s|) and B(s,t) = \mathsf {T}.
In other words, s \in D if and only if there is a (not too big) certificate “proving” it, which can be efficiently checked. That is, if the answer for the input s is supposed to be \mathsf {T}, then there is a certificate t that proves it: the certifier algorithm B, when run on s and t, will return \mathsf {T}. Conversely, if s \notin D, there is no t that works: B will never return \mathsf {T} for a certificate t unless s really is in D.
Example Polnomial-time certifier for IND-SET [00VW]
- December 2, 2026
For example, again thinking about IND-SET, s is of course a description of a graph G and a number k; a certificate t is simply a list of vertices S; the algorithm B checks whether |S| \geq k and whether each pair of vertices in S is not connected by an edge in G. This takes something like \Theta (|S|^2) time which is clearly polynomial in the size of the graph, since |S| \leq |V|.
Definition \mathcal {NP} [00VX]
- December 2, 2026
\mathcal {NP} is defined as the set of all decision problems which have a polynomial-time certifier.
Example \mathcal {NP} problems so far [00VZ]
- December 2, 2026
For example, 3-SAT, VERTEX-COVER, and IND-SET are all in \mathcal {NP} according to our discussion above.
Remark \mathcal {NP} = nondeterminism [00W0]
- December 2, 2026
\mathcal {NP} stands for “nondeterministic polynomial time”. The idea is that if we could make nondeterministic choices (i.e. choose multiple things at once and try them in parallel), we could solve any \mathcal {NP} problem in polynomial time: just nondeterministically make all possible choices for the certificate t and check them all at the same time.
\mathcal {P} vs \mathcal {NP} [00W1]
- December 2, 2026
What is the relationship between \mathcal {P} and \mathcal {NP}? We can first observe that:
Theorem \mathcal {P} \subseteq \mathcal {NP} [00W2]
- December 2, 2026
Proof.
- December 2, 2026
Question Does \mathcal {P} = \mathcal {NP}? [00W3]
- December 2, 2026
The question of whether \mathcal {P} = \mathcal {NP} is literally worth $1 million (it is one of the seven “Millenium Prize Problems” published by the Clay Mathematics Institute). It seems too good to be true, and most believe the answer is no. But this seems extremely difficult to prove.
Remark [00W4]
- December 2, 2026
We now understand the technical definition of the famous P vs NP problem; but what is not yet obvious is why this problem is interesting. To understand that, we must first build up some machinery around the idea of reducing one problem to another.
Reducibility and \mathcal {NP}-completeness [00UY]
- November 30, 2026
Reducibility [00WC]
- December 3, 2026
Suppose we have an algorithm to solve problem B, which we can think of as a black box that takes some inputs describing a problem instance and yields an appropriate output:
We can then think of our algorithm as a “subroutine” to turn it into a solution to another problem:
- The function f translates inputs for problem A into inputs for problem B.
- The function g translates outputs for problem B into outputs for problem A.
- Note we can even allow multiple “calls” to B.
Of course, this is only useful if this really does solve problem A. That is, we need the property that if y is a solution of problem B for input f(x), then g(y) is a solution of problem A for input x. In this case we write A \leq B (“A is reducible to B”). Note we can prove such a reduction without having an actual algorithm to solve problem B: we just show that if we had an algorithm to solve B then we could also use it to solve A.
Poly-time reducibility [00WK]
- December 3, 2026
We also typically care about how long the reduction takes.
Definition Polynomial-time reducibility [00WD]
- December 3, 2026
If A \leq B and the translation functions f and g take polynomial time to compute, and the reduction makes only a polynomial number of subroutine calls to B, then we say that A is polynomial-time reducible to B, and write A \leq _P B.
Example Bipartite matching \leq _P max flow [00WE]
- December 3, 2026
As we saw earlier in the semester, finding bipartite matchings is poly-time reducible to max flow. The "translation functions" only take an amount of time which is linear (hence polynomial) in the size of the input graph.
Example IND-SET and Reducibility and \mathcal {NP}-completeness [00WF]
- December 3, 2026
As another simple example, we saw that IND-SET \leq _P VERTEX-COVER and vice versa: given a graph G = (V,E) and natural number k as input, all the translation function f has to do is replace k by |V| - k.
Example 3-SAT \leq _P SAT [00WG]
- December 3, 2026
Clearly 3-SAT \leq _P SAT: any instance of 3-SAT is in fact a valid instance of SAT as well, so the "reduction" doesn't even have to do any work.
It turns out (but is extremely nonobvious!) that the other direction is true as well: SAT \leq _P 3-SAT (we will prove this eventually). So in some sense even though the special case of 3-SAT seems like it might be “easier” than the general case of SAT, it is not.
Why 3, you ask? Because 3 is the smallest k for which k-SAT is just as hard as SAT. It turns out that 2-SAT, where all clauses have exactly two variables, is much easier, and can even be solved in linear time. (1-SAT, of course, is trivial (though not as trivial as 0-SAT).)
Lemma Poly-time reducibility preserves poly-time solvability [00WL]
- December 3, 2026
Suppose A and B are decision problems with A \leq _P B. If B is solvable in polynomial time, then so is A.
Proof.
- December 3, 2026
Suppose we have an input x to A of size n. Suppose the translation function f (which converts x into an input suitable for B) takes time p(n) to compute, for some polynomial p. Note that this means the size of f’s output is also O(p(n)), since it takes p(n) time and it has to produce the entire output in that time.
Now suppose B can be solved in time q(m), where q is a polynomial and m is the size of its input. Then the total time to solve problem A on input x, using the reduction to B, is the time to convert the input plus the time to run B on an input of size O(p(n)), that is, p(n) + q(p(n)). Since p and q are polynomials, and polynomials are closed under addition and substitution, this is a polynomial.
Remark [00WM]
- December 3, 2026
It is not too hard to extend the above lemma and proof in a couple ways:
- If A and B are not decision problems then we must also take into account the time needed to run the output conversion.
- We can also take into account the case where B is called a polynomial number of times as a subroutine—it essentially involves multiplying by another polynomial, though to do it formally one has to be a bit more careful to state that we have not just a single input conversion function but many, which are all bounded by some polynomial runtime.
Corollary [00WN]
- December 3, 2026
Suppose A \leq _P B. If A is not solvable in polynomial time, then neither is B.
Remark [00WO]
- December 3, 2026
Intuitively, if A \leq _P B then B is “at least as hard as” A (that is, with respect to solvability in polynomial time).
Lemma Properties of \leq _P [00WP]
- December 3, 2026
\leq _P is reflexive and transitive.
Proof.
- December 3, 2026
Theorem 3-SAT \leq _P IND-SET [00WQ]
- December 3, 2026
Although the two problems seem totally unrelated, it turns out that we can reduce 3-SAT to IND-SET (in fact, as we will see, we can reduce in the other direction as well)!
Proof.
- December 3, 2026
We want to exhibit a polynomial reduction from 3-SAT to IND-SET. That is, given a black box to solve IND-SET, we want to show how we could use it to solve 3-SAT, using only a polynomial amount of additional work.
Given a set of 3-SAT clauses, we want to find a satisfying assignment, which has to make each clause true. In order to make a clause true it suffices to choose exactly one term from each clause which will be set to \mathsf {T}. (Note that “setting \overline {x_i} to True” of course means setting x_i to \mathsf {F}.) However, we have to choose consistently: we can never pick both x_i and \overline {x_i}.
We start by constructing a graph G with 3k vertices arranged in k triangles, like so:
Each triangle corresponds to a clause, and each vertex corresponds to a term; in particular, label v_{ij} by the jth term from clause C_i. So, for example, given the clauses (x_1 \lor \overline {x_3} \lor x_4), (x_2 \lor x_1 \lor x_3), (\overline {x_1} \lor x_3 \lor \overline {x_4}), we would start by constructing the graph
This graph always has independent sets of size k (but no bigger): just pick exactly one node from each triangle. However, we don’t want to allow picking just any old combination of nodes. So we add more edges: in particular, add an edge between every pair of nodes labelled by x_i and \overline {x_i} for some i. So our example graph becomes:
An independent set can’t contain both endpoints of an edge. These edges therefore encode the constraint that we have to choose variables consistently: we can never choose both x_i and \overline {x_i}.
The claim is now that this graph has an independent set of size \geq k iff the original 3-SAT instance is satisfiable—and hence we can solve the original 3-SAT instance by asking our black box for whether this graph has an independent set of size \geq k. If the graph has an independent set of size \geq k, it must in fact have size exactly k and consist of a choice of one term from each clause. Just making these terms \mathsf {T} will result in a satisfying assignment (variables which do not correspond to any chosen term can be set to anything, say, \mathsf {F}); this is well-defined because we will never have both x_i and \overline {x_i} selected (because of the extra edges we added). Conversely, if there is a satisfying assignment, just choose one vertex from each triangle whose label is \mathsf {T} under the assignment (since it is a satisfying assignment, each clause must have at least one term which is \mathsf {T}). Any two vertices connected by an edge are either in the same triangle (and we only pick one vertex from each triangle) or are labelled with inverse terms (and hence can’t both be labelled \mathsf {T}), so this is an independent set of size k.
Finally, this reduction does only a polynomial amount of work: given k clauses we construct a graph with \Theta (k) vertices and O(k^2) edges.
\mathcal {NP}-hardness [00WH]
- December 3, 2026
Definition \mathcal {NP}-hard [00WI]
- December 3, 2026
A decision problem X is \mathcal {NP}-hard if for all D \in \mathcal {NP}, D \leq _P X.
Remark Intuition for \mathcal {NP}-hardness [00WJ]
- December 3, 2026
Intuitively, a problem is \mathcal {NP}-hard if it is “at least as hard as everything in \mathcal {NP}”. It seems reasonable that there might be some extremely hard problems which fit the bill—though how on earth would we go about proving it? To show that X is \mathcal {NP}-hard, we have to somehow show that every \mathcal {NP} problem can be reduced to X, which at first glance seems impossible.
Lemma Chaining \mathcal {NP}-hardness [00WR]
- December 4, 2026
If X is \mathcal {NP}-hard and X \leq _P Y then Y is \mathcal {NP}-hard.
Proof.
- December 4, 2026
So, if we can find just one \mathcal {NP}-hard problem, we can potentially use this lemma to find others.
\mathcal {NP}-completeness [00WT]
- December 4, 2026
Definition \mathcal {NP}-complete [00WS]
- December 4, 2026
A decision problem X is \mathcal {NP}-complete if both X \in \mathcal {NP} and X is \mathcal {NP}-hard.
Remark [00WU]
- December 4, 2026
It is not at all clear that any such problems exist at all! We could just as easily imagine a situation where there are just a bunch of problems in \mathcal {NP} which are “maximally hard”—that is, no other problems in \mathcal {NP} are harder—but are still not harder than everything in \mathcal {NP}. Or we could imagine that the only problems harder than everything in \mathcal {NP} are themselves so hard that they are not in \mathcal {NP}.
Proposition \mathcal {NP}-completeness and \mathcal {P} vs \mathcal {NP} [00WV]
- December 4, 2026
If a decision problem X is \mathcal {NP}-complete, then X is solvable in polynomial time if and only if \mathcal {P} = \mathcal {NP}.
Proof.
- December 4, 2026
(\Longrightarrow ) If X is solvable in polynomial time, then by a previous lemma, any Y with Y \leq _P X is also solvable in polynomial time. But if X is \mathcal {NP}-complete then by definition it is \mathcal {NP}-hard, meaning that every problem in \mathcal {NP} is reducible to X and hence solvable in polynomial time.
(\Longleftarrow ) If X is \mathcal {NP}-complete then by definition X \in \mathcal {NP}, so if \mathcal {P} = \mathcal {NP} then X \in \mathcal {P}.
Corollary [00WW]
- December 4, 2026
If you come up with a polynomial-time algorithm to solve an \mathcal {NP}-complete problem, you win $1 million.
Remark [00WX]
- December 4, 2026
Good luck. Note that this is not just theoretical; it turns out that there are a great many \mathcal {NP}-complete problems that people actually care about on a practical level. So lots of smart people have been trying hard for a long time to develop good algorithms to solve them, but no one has ever come up with any polynomial-time algorithms for any of them.
The first \mathcal {NP}-complete problem [00WY]
- December 4, 2026
Definition Boolean circuit [00WZ]
- December 4, 2026
A boolean circuit is a directed, acyclic graph G such that:
- Each indegree-0 vertex (“input”) is labelled with either \mathsf {T}, \mathsf {F}, or a distinct variable.
- All other vertices have indegree 1 or 2, and are labelled with either \neg (if indegree 1) or \lor or \land (if indegree 2).
- Only one vertex has outdegree 0, which we call the “output”.
(Note this is not really a “circuit” as we would usually conceive it, since in particular there are no loops!)
Remark [00X2]
- December 4, 2026
Given a truth assignment for the variables labelling the inputs, we think of a Boolean circuit as resulting in a \mathsf {T} / \mathsf {F} value in the obvious way: each edge corresponds to a wire which carries a single \mathsf {T} / \mathsf {F} value to the input of the next logic gate. Boolean circuits come with a natural decision problem.
Problem CIRCUIT-SAT [00X0]
- December 4, 2026
Given a boolean circuit, is there an assignment of the input variables such that the circuit outputs \mathsf {T}?
Theorem CIRCUIT-SAT is \mathcal {NP}-complete [00X1]
- December 4, 2026
Around 1971, Stephen Cook and Leonid Levin independently proved that \mathcal {NP}-complete problems exist, although their proofs were a bit different than the one presented here.
Proof.
- December 4, 2026
First, it is easy to see that CIRCUIT-SAT \in \mathcal {NP}: a certificate is a truth assignment; to verify it in polynomial time we can just run the circuit and check that it outputs \mathsf {T}.
Now we must show CIRCUIT-SAT is \mathcal {NP}-hard. Suppose X \in \mathcal {NP}, i.e. X has a polynomial-time certifier B. We must show X \leq _P CIRCUIT-SAT.
Since B is an algorithm, it can be encoded as a boolean circuit (proof: computers exist, and any boolean function can be encoded using \land , \lor , \neg ). Well, except for one problem: our boolean circuits have no loops. But we can circumvent that by simply “unrolling” any loops, by making a whole bunch of copies of a circuit that computes a single step. If the algorithm only runs for a polynomial amount of time then we need at most a polynomial number of copies to make this work. So, intuitively, we can build a polynomial-sized boolean circuit that simulates the algorithm B. Given an input s, we fix the inputs corresponding to s, and leave as variables the inputs corresponding to t. Now we ask whether the resulting circuit is satisfiable. If it is, that means there is some t such that B(s,t) = \mathsf {T}, that is, s \in X. If it is not satisfiable, then there is no such t, so s \notin X. Hence X \leq _P CIRCUIT-SAT.
Now that we know there is one \mathcal {NP}-hard problem, finding others is a lot simpler!
Theorem [00X3]
- December 4, 2026
Corollary [00X4]
- December 4, 2026
SAT, IND-SET, and Vertex cover are all \mathcal {NP}-complete.
Proof.
- December 4, 2026
Remark [00X5]
- December 4, 2026
This is amazing. Just by looking at the definitions it wasn’t at all clear whether we would be able to find a single problem which was \mathcal {NP}-complete, and now we have found five. In fact, it turns out that we currently know of hundreds of “natural” problems which are \mathcal {NP}-complete. Richard Karp got this all started with his 1979 paper proving 21 different \mathcal {NP}-hard problems.
So, the “reason” CIRCUIT-SAT is \mathcal {NP}-hard is that we can use it to model arbitrary computation, by essentially building a little computer. But think about what this transitive chain of reductions is then showing us: we can take a circuit modelling a computer and reduce it to a 3-SAT instance which models the same computer. But we can then in turn take that 3-SAT instance modelling a computer and reduce it to a graph, such that finding an independent set of a certain size in the graph models the same computation! Computation is sneaky like that; you end up finding it in places you would not expect. Who would have guessed that finding independent sets in a graph turns out to be equivalent to doing arbitrary computation? But in some sense \mathcal {NP}-complete problems are like this, and this gives us some intuition as to why they are so hard to analyze: because you can smuggle arbitrary computation into them!
Super Mario Bros is \mathcal {NP}-hard [00X6]
- December 4, 2026
See this 2012 paper by Aloupis et al. showing that Super Mario Bros (and a bunch of other classic video games) are \mathcal {NP}-hard, in the sense that it is hard to decide whether a given level can be beaten or not. The proof is by reduction from 3-SAT.