Algorithms problems [00JL]
- August 26, 2026
This page collects the problems available for you to solve on problem sets.
Intro/review problems
- August 26, 2026
The problems in this section are intended to help you review key ideas from Data Structures and Discrete Math that we will be using a lot in this class. If you are unsure about anything here, use it as an opportunity to review or ask for help!
[RH] Repeated halving (1 pt) [00JK]
- August 26, 2026
How many times do you have to repeatedly halve 32 in order to reach 1 (or, put another way, how many times do you have to repeatedly double 1 in order to reach 32)? What about 8192? Consider the function which given an input n, outputs the number of times n can be repeatedly halved before falling below 1. What is the common mathematical name for this function?
[I1] Recurrence (2 pts) [00JM]
- August 26, 2026
Let p_n be defined for all n \geq 0 by \begin {align*} p_0 &= 0 \\ p_n &= 2p_{n-1} + 1 && (n > 0) \end {align*} State and prove a closed (that is, non-recursive) formula for p_n.
(If you need a refresher on recursion and induction, there are a lot of resources posted on the course website!)
[O1] Big-O review (3 pts) [00JN]
- August 26, 2026
For each of the following, answer with the best (smallest) upper bound from this list: O(1), O(\log n), O(n), O(n \log n), O(n^2), O(2^n). Give a brief justification for each.
- Number of leaves in a depth-n balanced binary tree
- Depth of an n-node balanced binary tree
- Number of edges in an n-node tree
- Time needed to sort a list of n items using merge sort
- Number of distinct subsets of a set of n items
- Number of bits needed to represent the number n in binary
- Time needed to find the closest pair of points among n points in Euclidean space by simply listing all the pairs
- Time needed to insert n items into a binary heap
- Time needed to find the second largest number in a sorted list of n distinct numbers
- Time needed to find the second largest number in an unsorted list of n distinct numbers
Big-O is not about time! [00JS]
- August 27, 2026
Students coming out of data structures often think that big-O is specifically about measuring how long algorithms take, but it is not. Big-O is a tool for measuring the rate of growth of one thing relative to another. We often do use it to measure the rate of growth of the time needed to run an algorithm relative to the size of the input, but we can use it to measure rates of growth of other things as well, such as the amount of memory used relative to the size of the input, the height of a tree relative to the width, and so on.
So, for example, you should not assume that the questions in [O1] Big-O review (3 pts) are asking about time unless they explicitly say so. For example, part (a) is asking how many leaves there are in a tree with a depth of n, that is, how fast does the number of leaves grow relative to the depth? It is not asking how long it would take to find those leaves.
[K1] Kattis: Akcija (1pt) [00JO]
- August 27, 2026
Solve Akcija.
Tips on solving Kattis problems [00JP]
- August 27, 2026
Throughout the semester, I will occasionally assign programming challenges from Open Kattis. These problems will help you translate theory into practice by writing working implementations of algorithms or concepts we have been discussing in class.
I am very aware that solutions to Kattis problems can easily be found online, and LLMs can solve many of them. I trust you not to look at any such solutions. You only get the benefit of these problems by solving them on your own (not to mention that doing otherwise would be an academic integrity violation).
Solving
- August 27, 2026
You can implement your solution in any
programming language you wish. Kattis always expects you to submit
a program that reads from standard input and writes to
standard output. For example, in Python, that means using
input() to read the input and print() to produce output.
In Java, you can use Scanner and System.out.println, and so
on.
If you'd like additional hints on how to parse the input, how to access standard data structures in your chosen programming language, etc., just ask!
Submitting
- August 27, 2026
To submit your solution to a Kattis problem, you must submit both:
- A screenshot showing that Kattis accepted your submission
- Your code. Note, do not submit a screenshot of your code, and do not submit a project folder containing a zillion auto-generated files! Just submit a single
.pyor.javafile (for example—you can also use other languages besides Python and Java).
[K2] Kattis: Backspace (1 pt) [00JQ]
- August 27, 2026
[K3] Kattis: Forests (1pt) [00JR]
- August 27, 2026
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 problems [00KJ]
- September 8, 2026
Problems related to asymptotic analysis.
[O2] Algorithm input sizes by runtime (1 pt) [00KK]
- September 8, 2026
Suppose you have algorithms with the six running times listed below. (Assume these are the exact number of operations performed as a function of the input size n.) Suppose you have a computer that can perform 10^{10} operations per second, and you need to compute a result in at most an hour of computation. For each of the algorithms, what is the largest input size n for which you would be able to get the result within an hour? For answers smaller than 10^{10}, give your answer as an exact integer; for larger answers you may provide an approximation.
Hint.
- September 8, 2026
Most of these can be solved algebraically, but for at least one you may need to resort to numeric methods (e.g. use Wolfram Alpha or write a bit of code yourself).
- n^2
- n^3
- 100n^2
- n \log _2 n
- 2^n
- 2^{2^n}
- n!
[O3] Some asymptotic properties (2 pts) [00KL]
- September 8, 2026
Little-o notation [00KM]
- September 8, 2026
In addition to O, \Theta , and \Omega , we will also sometimes use the notation o(g(n)) (little-o) to mean that a function is O(g(n)) but not \Theta (g(n)). So, if \lim _{n \to \infty } T(n)/g(n) = 0, then T(n) is o(g(n)). Intuitively, if big-O is like “less than or equal to”, little-o is like “less than”; if f(n) is o(g(n)) then f “grows strictly more slowly than” g.
- Show that n^j is o(n^k) whenever j < k.
- Prove that \log _a n is \Theta (\log _b n) for any positive
integer bases a,b > 1. Conclude that we are justified in writing
simply \Theta (\log n) without caring about the base of the
logarithm.
Hint.
- September 8, 2026
Recall, or look up, the logarithm change-of-base formula.
- Prove that \log _b n is o(n^x) for any b > 1 and x > 0.
Hint.
- September 8, 2026
Use l'Hôpital's rule.
- Prove that n^k is o(b^n) for any positive integer k and
any real number b > 1. For example, n^{295} is
o(1.0001^n). In the long run, any polynomial function grows
more slowly than any exponential function!
Hint.
- September 8, 2026
Use induction and l'Hôpital's rule.
[O4] Function ordering (1 pt) [00L5]
- September 11, 2026
Take the following list of functions and arrange them in ascending order of asymptotic growth rate. That is, if function g(n) immediately follows function f(n) in your list, then it should be the case that f(n) is O(g(n)). Please prove/justify your claims by making reference to theorems from class or the previous problem.
- f_{1}(n) = n^{2.5}
- f_{2}(n) = \sqrt {2n}
- f_{3}(n) = n + 10
- f_{4}(n) = 10^n
- f_{5}(n) = 100^n
- f_{6}(n) = n^2 \log n
[O5] Characterizing asymptotic behavior (4 pts) [00L6]
- September 11, 2026
Characterize the asymptotic behavior of each of the following in terms of n, using \Theta . Give a brief justification for each answer. For items asking for the time needed to perform some operation or solve some problem, you should describe the worst case running time of the best possible algorithm.
- 1 + 2 + 3 + 4 + \dots + n
- Average number of array lookups needed to find a given element in a sorted array of length n.
- Number of two-element subsets of a set of size n.
- 1 + 2 + 4 + 8 + \dots + 2^n
Total number of nodes in a complete binary tree with n leaves. A complete binary tree is one where every node has two children except for the leaves on the last level. For example, the complete binary tree shown below has 8 leaves.
Number of edges in a graph with n nodes, where every node is connected to every other node.
- Number of different ways to arrange n people in a line.
- Average number of steps needed to find a given element in a sorted linked list of length n.
- Biggest integer that can be represented with n bits.
- Worst-case number of swaps needed to sort an array of length n if you are only allowed to swap adjacent elements.
- Worst-case number of steps needed to check whether two lists, each containing n integers (not necessarily sorted), have any element in common.
Hint.
- September 11, 2026
\Theta (n^2) is too slow!
- Number of array lookups performed by this Python code:
for i in range(0,n): for j in range (0,i): sum += array[i][j] - Number of addition operations performed by this Java code:
for (int i = 0; i < n; i += 3) { sum = sum + i; } - Total number of calls to
printlnperformed by this Java code:for (int i = 1; i < n; i *= 2) { for (j = 0; j < 20; j++) { System.out.println(i + j); } } - Total number of calls to
printperformed by this Python code:def foo(n): print(n) if n > 0: foo(n-1) foo(n-1)
[O6] Dropping jars (3 pts) [00L7]
- September 11, 2026
You’re doing some stress-testing on various models of glass jars to determine the height from which they can be dropped and still not break. The setup for this experiment, on a particular type of jar, is as follows. You have a ladder with n rungs, and you want to find the highest rung from which you can drop a copy of the jar and not have it break. We call this the highest safe rung.
It might be natural to try binary search: drop a jar from the middle rung, see if it breaks, and then recursively try from rung n/4 or 3n/4 depending on the outcome. But this has the drawback that you could break a lot of jars in finding the answer.
If your primary goal were to conserve jars, on the other hand, you could try the following strategy. Start by dropping a jar from the first rung, then the second rung, and so forth, climbing one higher each time until the jar breaks. In this way, you only need a single jar—at the moment it breaks, you have the correct answer—but you may have to drop it n times (rather than \lg n times as in the binary search solution).
So here is the trade-off: it seems you can perform fewer drops if you’re willing to break more jars. To understand better how this trade-off works at a quantitative level, let’s consider how to run this experiment given a fixed “budget” of k \geq 1 jars. In other words, you have to determine the correct answer—the highest safe rung—and can use at most k jars in doing so.
- Suppose you are given a budget of k = 2 jars. Describe a strategy for finding the highest safe rung that requires you to drop a jar at most f(n) times, for some function f(n) that grows slower than linearly. (In other words, f(n) should be o(n), that is, \lim _{n \to \infty } f(n)/n = 0.)
- Now suppose you have a budget of k > 2 jars, for some given k. Describe a strategy for finding the highest safe rung using at most k jars. If f_k(n) denotes the number of times you need to drop a jar according to your strategy, then the functions f_1, f_2, f_3, \dots should have the property that each grows asymptotically slower than the previous one: \lim _{n \to \infty } f_k(n)/f_{k-1}(n) = 0 for each k.
Graph problems [00LW]
- September 14, 2026
Problems related to graphs.
[G1] Adjacency matrices (1 pt) [00LX]
- September 14, 2026
Given a simple graph G with vertices numbered from 1 to n, an adjacency matrix for G is an n \times n matrix A where A[i,j] = 1 if i and j are adjacent, and A[i,j] = 0 otherwise. In other words, the entry at row i and column j tells us whether there is an edge between i and j, with 1 for yes and 0 for no.
- Make a drawing of the graph represented by the adjacency matrix \begin {bmatrix} 0 & 0 & 1 & 1 \\ 0 & 0 & 1 & 0 \\ 1 & 1 & 0 & 1 \\ 1 & 0 & 1 & 0 \end {bmatrix}.
- Given a vertex u and the adjacency matrix A, how long does it take to list all the neighbors of u: \Theta (n), or \Theta (\deg (u))? Why?
- A directed graph is a graph where each edge has a particular direction, that is, an edge is an ordered pair of vertices rather than just a set of two vertices. Typically such graphs are drawn with a little arrow on each edge showing which direction it goes. Explain how to generalize adjacency matrices to represent directed graphs.
- A weighted graph is a graph where each edge has an associated number, or weight, representing something like cost, time, or distance. Explain how to generalize adjacency matrices to represent weighted graphs.
- (Advanced, optional) Let A be the adjacency matrix for a simple (undirected, unweighted) graph G. What information does the matrix A^2 represent? What about A^3? In general, what about A^n?
[G2] Adjacency lists (1 pt) [00LY]
- September 14, 2026
Given a simple graph G, an adjacency list representation for G consists of a map (aka dictionary) associating each vertex with the list (or set) of all its adjacent neighbors. In other words, using Java-like notation, Map<Vertex, List<Vertex> >.
- Make a drawing of the graph represented by the map \{ 1 \mapsto [3,4], 2 \mapsto [3], 3 \mapsto [1, 2, 4], 4 \mapsto [1, 3] \}.
- Given a vertex u and an adjacency list representation of a graph G, how long does it take to list all the neighbors of u: \Theta (n), or \Theta (\deg (u))? Why?
- Explain how to generalize adjacency lists to represent directed graphs.
- Explain how to generalize adjacency lists to represent weighted graphs.
[G3] Connectivity from degree (2 pts) [00LZ]
- September 14, 2026
Let G=(V,E) be an undirected graph with n vertices, with no self-loops (that is, no edges of the form (v,v) from a vertex to itself). Show that if every vertex has degree at least n/2, the graph is connected. If it makes your proof easier, you may assume that n is even.
Hint.
- September 14, 2026
Think about cuts in the graph. A cut (S,T) is a partition of the vertices into two sets S and T such that every vertex is in either S or T but not both. Is it possible to have a cut (S,T) with no edges between S and T?
[G4] Handshake lemma (1 pt) [00M5]
- September 16, 2026
Prove/explain why the sum of all vertex degrees in a graph is equal to twice the number of edges. Your proof need only be a sentence or two.
[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).
[G6] Distances in a tree (3 pts) [00MF]
- September 18, 2026
Given a graph T which is guaranteed to be a tree, and a particular starting vertex s, design an O(V + E) algorithm to find the distance of every vertex from s. In other words, your algorithm should output some kind of dictionary/map or array associating every vertex v to a natural number \ell (v) which is the length of a path from s to v. Note that the length of a path from s to itself is 0, the length of a path from s to any of its neighbors is 1, and so on.
You may assume that T is represented in whichever way is easiest for you (adjacency matrix or adjacency list).
Explain how your algorithm works, and analyze its asymptotic running time. Psuedocode is fine, though you may also choose to write real code if you wish.
[G7] Connected component labelling (3 pts) [00MG]
- September 18, 2026
Given a graph G with n vertices labelled 0 through n-1, design an O(V+E) algorithm to find and label all the connected components of G. That is, your algorithm should output a dictionary or array associating each vertex v with a component label c(v) such that two vertices u and v have the same component label (that is, c(u) = c(v)) if and only if u and v are connected. For example, you might give all the vertices in the first connected component the label 1, all the vertices in the second connected component the label 2, and so on.
You may assume that G is represented in whichever way is easiest for you (adjacency matrix or adjacency list).
Explain how your algorithm works, and analyze its asymptotic running time. Psuedocode is fine, though you may also choose to write real code if you wish.
[K5] Kattis: Sky Islands (2 pts) [00MH]
- September 18, 2026
[K6] Kattis: Reachable Roads (2 pts) [00MI]
- September 18, 2026
[K7] Kattis: BFS problem I (2 pts) [00MS]
- September 21, 2026
Solve any one of the following Kattis problems:
[K8] Kattis: BFS problem II (2 pts) [00MT]
- September 21, 2026
Solve another one of the problems from [K7] Kattis: BFS problem I (2 pts).
[G8] BFS layers in a graph of bitstrings (2 pts) [00MU]
- September 21, 2026
Consider the family of undirected graphs \mathcal {H}_k defined as follows. \mathcal {H}_k has 2^k vertices labelled with the integers 0 through 2^k - 1. Vertices u and v are connected by an edge if and only if the binary representations of u and v differ in exactly one bit position. For example, in \mathcal {H}_4, the vertices 5 and 13 are connected by an edge since 5 = 0101_2 and 13 = 1101_2 differ in the first bit position, but the rest of the bits are the same.
Consider doing a BFS in \mathcal {H}_{10} starting at node 0. How many vertices are in L_6, that is, the sixth layer generated by the BFS? Give your answer together with either a proof, or the program you used to calculate the answer. Either approach will receive full credit. (Hint if you choose to write a program: to flip the jth bit of an integer n, you can use n ^ (1 << j), that is, the bitwise XOR of n with the result of shifting 1 left j times, that is, 2^{\texttt {j}}. These operators are valid in many languages such as Java, Python, and C/C++.)
[G9] Shortest path in a large random graph (3 pts) [00MV]
- September 21, 2026
The file graph-F26.txt describes a large undirected graph. The first line of the file contains a single integer which is the number of edges in the graph. Each subsequent line of the file describes one (undirected) edge, and contains two space-separated strings which are the names of the two vertices at the endpoints of the edge.
Write a program (in a programming language of your choice) to find a shortest path from the vertex labelled with your first name to the vertex labelled END (if there are multiple shortest paths you can find any one of them). You should submit a text file containing the list of vertices along this shortest path, starting with your name and ending with END. Each vertex should be on a separate line. For example, my solution looks like this:
Brent j2l65t dae18w kr9stg 8km7u3 j14vln a0pjwk END
You should also turn in the code you used to find your path.
To avoid any ambiguity, the list of names I used was as follows: Amiko, Coen, Collin, David, Jack, Jaxon, Jordan, Mark, Natalia, Rayden, Spencer, Tanvi, Vincent.
[G10] Strong connectivity (3 pts) [00MW]
- September 21, 2026
In class, we saw the definition of an undirected graph which is connected: a graph is connected if there is always a path between any two vertices. When we add directions to the edges, the concept of connectedness becomes more interesting.
A directed graph is strongly connected if for any two vertices x and y, there is always a directed path from x to y. Note this must also be true for the vertices y and x, so there must be a directed path from y to x as well. In other words, a strongly connected graph is like a network of one-way streets where it is always possible to drive from any location to any other location while obeying the one-way signs; you can never get stuck.
This problem will walk you through the process of developing an algorithm for determining whether a directed graph is strongly connected.
- Give an example of a strongly connected graph with at least 4 vertices (you may either draw it, or list its vertices and edges).
- Prove: a directed graph G is strongly connected if and only if there is some vertex s such that s is mutually connected to every other vertex; that is, for every other vertex v there is both a directed path from s to v and also from v back to s.
- Explain how to use a graph search algorithm like DFS or BFS to determine whether there exist directed paths from a particular starting vertex s to every other vertex.
- Explain how to determine, in only O(V+E) time, whether there exist directed paths to a particular vertex s from every other vertex.
- Put all these observations together into an algorithm to determine whether a given directed graph is strongly connected. You should:
- Describe your algorithm. You may use pseudocode, but your description should be detailed enough that someone could take it and turn it into working code.
- Prove/justify the correctness of your algorithm. In other words, why does your algorithm correctly determine whether a graph is strongly connected? Of course, you may freely cite the results from the previous parts of this problem.
- Analyze the asymptotic running time of your algorithm.
[G11] Kahn's algorithm and directed cycles (2 pts) [00NV]
- October 3, 2026
In class we explored Kahn's algorithm, which can be used to find a topological ordering of any DAG. Explain how we could extend Kahn's algorithm to find a directed cycle in directed graphs which are not a DAG.
How can we tell when Kahn's Algorithm has failed to find a topological ordering? What can we say about the indegree of all the vertices that are left? What happens if you pick a random starting vertex in the leftover graph and follow edges backwards?Hint.
Hint.
Greedy algorithm problems [00NR]
- October 3, 2026
Dijkstra's algorithm problems [00NS]
- October 3, 2026
[D1] Dijkstra with negative weight (1pt) [00NT]
- October 3, 2026
Why doesn't Dijkstra's algorithm work if edges in the graph can have negative weights (even if there are no directed cycles)? Give an example of a directed graph with no directed cycles where Dijkstra's algorithm fails to find the minimum-weight path between a pair of vertices. Be sure to demonstrate that you understand why your graph is a counterexample; that is, show what Dijkstra's algorithm does on your example graph, and explain why the path it finds is not the minimum-weight path.
[D2] Dijkstra for longest paths (1pt) [00NU]
- October 3, 2026
What happens if we replace the word “smallest” in Dijkstra’s algorithm with the word “biggest”—that is, we use a max priority queue so we pull out the vertex u with the maximum distance on each iteration, and for each edge (u,v) we update d[v] to be the maximum of d[v] and the sum d[u] + w_{uv}. Can we use this modified Dijkstra’s algorithm to find longest paths bewteen nodes in any graph without directed cycles? Prove that this works, or give a counterexample (with explanation) where it doesn’t.
[K9] Kattis: Dijkstra problem (3 pts) [00OS]
- October 9, 2026
Solve one of the following Kattis problems requiring Dijkstra's Algorithm:
[D3] The Roving Photographer (2 pts) [00OT]
- October 9, 2026
Phoebe the Photographer is just leaving for work at the small-town newspaper where she works as a staff photographer, when she suddenly remembers that she was supposed to take a photograph to decorate page C17. She will just have to take a photograph on the way, but she is worried about getting to work late!
Phoebe's town can be represented by a directed, weighted graph with V vertices and E edges, where the weight on each edge represents the time needed to travel along that street in the given direction. (As usual, two-way streets are represented by one edge in each direction, possibly with different weights.) One particular vertex represents Pheobe's house, and another vertex represents her work. There are various locations (i.e. vertices) at which Pheobe could take a photograph; each such vertex has a number representing the amount of time Pheobe would need to spend taking a photograph there (some photographs can be taken quickly, while others need a while to set up).
Pheobe needs to travel to some location where she can take a photograph, pause long enough to take the photo, and then travel to her workplace. Explain how Pheobe could compute such a path which is as short as possible, and analyze the running time of your algorithm.
Hint.
- October 9, 2026
You may come up with a \Theta (VE\lg V) algorithm, but it is possible to do better: it can be done in \Theta (E \lg V) time.
Hint.
- October 9, 2026
How can you transform the graph so that the problem is solved by a single call to Dijkstra's Algorithm?
Hint.
- October 9, 2026
Consider duplicating each vertex, one to represent visiting that location with no photograph taken, and another to represent visiting that location with a photograph already taken.
Minimum Spanning Tree problems [00OR]
- October 9, 2026
[M1] Kruskal's Algorithm works with repeated weights (3 pts) [00OO]
- October 9, 2026
On an activity, we proved that Kruskal's Algorithm is correct when every edge has a distinct weight. Prove that Kruskal's Algorithm works even when there are edges in the graph with the same weight.
Hint.
- October 9, 2026
Generalize the Cut Property to the situation when there are multiple edges with the same minimum weight crossing a cut. What can we say about the relationship of any MST to such edges?
[M2] Prim's Algorithm is correct (2 pts) [00OQ]
- October 9, 2026
Prove that Prim's Algorithm is correct.
[M3] Min-max spanning trees (3 pts) [00OU]
- October 9, 2026
Let G=(V,E) be an undirected, connected graph with non-negative edge lengths. We say that T is a min-max spanning tree on G if T is a spanning tree whose longest edge is as short as possible. That is, if we imagine taking all the possible spanning trees of G and sorting them by the length of their longest edge, in increasing order, T would be first (or tied for first) on the list. Put yet another way, T is a min-max spanning tree if and only if every other spanning tree T' has some edge which is longer than (or equal to) every edge in T.
Prove or disprove each of the following claims. (Hint: try lots of small examples!)
- If T is a minimum spanning tree for G, then T is a min-max spanning tree for G.
- If T is a min-max spanning tree for G, then T is a minimum spanning tree for G.
[K10] Kattis: MST problem (3 pts) [00P7]
- October 9, 2026
Solve one of the following Kattis problems requiring the computation of a minimum spanning tree:
[M4] Percolation (6 pts) [00P8]
- October 14, 2026
In this implementation challenge you will explore an interesting application of a union-find structure.
Introduction [00P9]
- October 14, 2026
Percolating on 25x25 grid...
. . . X . . . . . . .
. . . . X . . . . . .
. . . . . X X . . . . . . .
. . X X . . . . .
. . . . . . X . . . . . .
. . . . X . . . . . . . . . .
. . . . . . X . . . . . .
. . . . . X . . . . .
. . . . . . X X X . . . X X X . .
. . . . . . . . . . X . X X . X . . .
. . . . . . . X X . . X . . X . .
. . . . . . . . . X X X X . X . .
. . . . . . . . . X
. . . . . . . . . . . . X X .
. . . . . . . . . . . . . X
. . . . . . . X
. . . . . . . . X X .
. . . . . . . . . . X X X X .
. . . . X . . .
. . . . . . . . . . X . .
. . . . . . X . . . .
. . . . . . . . . X . . . . .
. . . . . . . . . X X . .
. . . . . . . . . X . .
. . . . . . . X .
Percolation achieved with 352 cells opened (56.32%)
Shortest path length = 48Imagine an n \times n square grid, where each cell is connected to its four neighbors to the north, east, south, and west. Each cell can be either “open” or “blocked”. Paths through the grid can only travel through open cells. We say the grid percolates if there is a path from some open cell in the top row all the way to some open cell in the bottom row.
Now, carry out the following process: the cells all start out blocked; at each iteration, randomly pick a blocked cell and open it. Keep iterating until the grid percolates. It is a curious fact that on average, the grid will percolate after 59.2% of the cells are opened—no matter what size the grid is. (The larger the grid, the more precise the percentage will be.) Moreover, this percentage is a sort of “phase transition”: if you take a large grid and randomly open fewer than 59.2% of its cells, then it probably will not percolate; open any more than 59.2%, and it probably will.
Requirements [00PA]
- October 14, 2026
Write a program (using a language of your choice) which will explore this percolation model, producing output like the above. That is, your program should carry out the above random cell-opening procedure until the grid percolates, and then display the resulting grid along with the shortest percolating path.
Note that in the given sample output shown above, open cells are displayed as a space, blocked cells as a dot, and open cells through which the shortest percolating path passes as an X. Alternate columns are left blank just to make the grid look relatively square. Your output does not have to look exactly like this.
To receive credit for this problem:
- Your program runs correctly and can produce output like the above.
- Your program runs within a few seconds for grids up to 500 \times 500 in size.
- Your implementation of a generic union-find data structure is in a separate file from the rest of your code (or a separate class within the same file).
Hints [00PB]
- October 14, 2026
- You’ll want to implement your own union-find data structure, as discussed in class. Make a generic union-find data structure which supports the following operations:
new(n: int): create a new union-find structure with n nodes, numbered 0 \dots n-1, with each node conceptually starting out in its own singleton set.find(u: int) -> int: return the “representative” or root node of the set containing node u.union(u: int, v: int): union the sets containing nodes u and v, if they are not already in the same set.connected(u: int, v: int) -> bool: test whether two nodes are already in the same set or not. This can be implemented simply in terms offind.
- If you want to assign a unique node number to each cell in an n \times n grid, it is easiest to number the first row 0 \dots n-1, then the second row n \dots 2n-1, and so on. In general, coordinates (r,c) will be node nr + c. Conversely, node k will correspond to the row and column coordinates (k \mathbin {\mathbf {div}} n, k \mathbin {\mathbf {mod}} n), i.e. the quotient and remainder when dividing k by n.
- We have discussed in class how to find a shortest path between two specific nodes. Since we want to find a path from any node in the top row to any node in the bottom row, try adding a new “virtual” start node connecting to every node in the top row, and a virtual end node connecting to every node in the bottom row. For example, these virtual nodes could be given node numbers n^2 and n^2 + 1 in a union-find structure of size n^2 + 2. This reduces the problem back to finding a path between two specific nodes (the virtual start and end nodes).
Divide & Conquer problems [00PM]
- October 19, 2026
[DC1] Modular exponentiation (2 pts) [00PN]
- October 19, 2026
Describe a recursive algorithm which computes the modular exponentiation b^e \bmod {m}, that is, the remainder when dividing b^e by m, in only O(\lg e) time. You may assume that 0 \leq b, e, m < 2^{32}, and that arithmetic operations such as addition and multiplication on 64-bit numbers take constant time.
Be sure to analyze the running time of the algorithm, and prove it is correct by (strong) induction on e.
Recall that (a \cdot b) \equiv _m (a \bmod m) \cdot (b \bmod m), so it does not matter whether you reduce modulo m before or after multiplication. For example, b^4 \bmod m \equiv _m (b \bmod m)^4.
[DC2] Majority elements (3 pts) [00PO]
- October 19, 2026
An array A[1\ldots n] is said to have a majority element if more than half of its entries are the same. Given an array, the task is to design an efficient algorithm to tell whether the array has a majority element, and, if so, to find that element. The only thing you may assume about the elements of the array is that you can test whether two of them are equal (in constant time). In particular, the elements of the array are not necessarily from some ordered domain like the integers, and so there can be no comparisons of the form A[i] > A[j]. You also may not assume that there is a hash function for the elements, so they cannot be used as the keys of a dictionary/hash table.
- What is a brute-force algorithm for this problem? How long does it take to run?
- Show how to solve this problem in O(n \log n) time. Make sure to prove that your algorithm is correct (via induction) and give a recurrence relation for the running time of your algorithm.
[DC3] n-bit multiplication (1 pt) [00PW]
- October 22, 2026
Explain how to generalize the divide-and-conquer n-bit multiplication algorithm from class to work for any value of n, not just powers of two.
[DC4] Divide & conquer comparison (1 pt) [00Q2]
- October 23, 2026
Suppose you are choosing between the following three algorithms:
- Algorithm A solves problems by dividing them into five subproblems of half the size, recursively solving each subproblem, and then combining the solutions in linear time.
- Algorithm B solves problems of size n by recursively solving two subproblems of size n-1 and then combining the solutions in constant time.
- Algorithm C solves problems of size n by dividing them into nine subproblems of size n/3, recursively solving each subproblem, and then combining the solutions in O(n^{2}) time.
[DC5] Efficient Fibonacci calculation (3 pts) [00Q3]
- October 23, 2026
Recall the Fibonacci numbers F_n:
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]
As you may know, directly turning the definition of Fibonacci numbers into a recursive implementation is a terrible idea; the resulting algorithm takes \Theta (\varphi ^n) time (where \varphi = (1 + \sqrt 5)/2 \approx 1.618\dots ).
The usual iterative algorithm to repeatedly calculate the next Fibonacci number from the previous two seems like it would take \Theta (n) time to compute F_n: it just loops from 1 to n and does one addition each loop, right? Well... yes, it does one addition each loop, but we can’t really assume that these additions take constant time, because the Fibonacci numbers involved can get quite large! Let’s analyze the situation more carefully.
- Recall from a previous homework problem that the size of the nth Fibonacci number F_n is \Theta (\varphi ^n). Given this fact, approximately how many bits (in terms of \Theta ) are needed to represent F_n? Simplify your answer as much as possible. (Note, you need note have completed GCD4 to do this problem.)
- Now suppose we implement the usual iterative algorithm as follows: initialize an array F of size n, which can hold arbitrary-size integers. Initialize F[0] = 0 and F[1] = 1. Then loop i from 2 to n, and at each iteration, set F[i] \gets F[i-1] + F[i-2]. Taking into account the time needed to add integers of a given size, what is the running time of this algorithm?
- We can do better! In addition to their definition, Fibonacci numbers satisfy the following recurrences (you can just take my word for it, or see this exercise):
\begin {align*}
F_{2n+1} & = F_n^2 + F_{n+1}^2 \\
F_{2n} &= 2F_n F_{n+1} - F_n^2
\end {align*} For example, F_7 = 13 = F_3^2 + F_4^2 = 2^2 + 3^2, and F_8 = 21
= 2F_4F_5 - F_4^2 = 2 \cdot 3 \cdot 5 - 3^2.
Explain how to turn these recurrences into a recursive algorithm for computing Fibonacci numbers, and implement this algorithm in a programming language of your choice. Be careful not to make more recursive calls than necessary!
- Analyze the running time of this algorithm. Be sure to include the time needed to do any additions or multiplications. Assume we will use Karatsuba’s algorithm for multiplication.
[DC6] Fibonacci recurrence (1 pt) [00Q4]
- October 23, 2026
This problem guides you through a derivation of the Fibonacci recurrences in the previous problem.
- Consider the 2\times 2 matrix M = \begin {bmatrix} 1 & 1 \\ 1 & 0 \end {bmatrix}. Compute M^2, M^3, and M^4. What do you notice?
- State a conjecture about the values of M^n for n \geq 1 and prove your conjecture by induction on n.
- In practice, of course, we could compute M^n using an algorithm like the one in DC1. Expand the equation M^{2n} = (M^n)^2 and use it to derive the Fibonacci recurrences in DC5.
Dynamic programming problems [00QM]
- October 27, 2026
Consulting business [00QN]
- October 27, 2026
The problems in this section all refer to the following scenario.
Scenario [00QO]
- October 27, 2026
You are running a consulting business, with clients on both east and west coasts. Each month, you can run your business from an office in either New York or San Fransisco. In month i, you will incur an operating cost of N_i if you run the business out of New York; you will incur an operating cost of S_i if you run the business out of San Fransisco (the costs can change each month depending on the distribution of client demands).
However, if you run the business out of one city in month i, and then out of the other city in month i+1, then you incur a fixed moving cost of M to switch cities.
Given a sequence of n months, a plan is a sequence of n locations—each one equal to either \mathsf {NY} or \mathsf {SF}—such that the ith location indicates the city in which you will be based in the ith month. The cost of a plan is the sum of the operating costs for each of the n months, plus a moving cost of M for each time you switch cities. The plan can begin in either city.
Given a value for the moving cost M, and sequences of operating costs N_1, \dots , N_n and S_1, \dots , S_n, the problem is to find a plan with minimum total cost.
[DP1] Greedy failure (1 pt) [00QP]
- October 27, 2026
Show that the following greedy algorithm does not correctly solve this problem, by describing inputs for which it does not return the correct answer.
In your example, be sure to explain what the correct answer is and also what the above algorithm finds.
[DP2] Consulting recurrence (1 pt) [00QQ]
- October 27, 2026
Let C(i,c) denote the minimum cost possible if you operate your business for only months 1 through i and end in city c. For example, C(3,\mathsf {NY}) denotes the minimum possible cost for the first three months (disregarding any following months) that end by operating out of New York in month 3.
Define C via a recurrence.
[DP3] Consulting algorithm (1 pt) [00QR]
- October 27, 2026
Describe an efficient algorithm that takes values for n, M, and sequences of operating costs N_1, \dots , N_n and S_1, \dots , S_n, and returns the cost of an optimal plan. Justify the correctness of your algorithm and analyze its asymptotic running time.
[DP4] Train track (2 pts) [00QS]
- October 27, 2026
You are building a toy train track out of a sequence of straight pieces laid end-to-end. Some pieces are one unit long, and some are three units long. How many different ways are there to build a track that is five hundred units long?
For example, there are 9 different ways to build a track that is 7 units long, as illustrated below.
Hint.
- October 27, 2026
Let T(n) denote the number of ways to build a track of length n, and come up with a recurrence for T. What are your choices for the final track segment?
Hint.
- October 27, 2026
To answer this you will need to write a small program. If you use Java, be sure to use BigInteger.
[DP5] Longest path in an ordered graph (3 pts) [00QT]
- October 27, 2026
Let G = (V,E) be a directed, unweighted graph with nodes v_1, \dots , v_n. We say that G is an ordered graph if it has the following properties:
- Each edge goes from a node with a lower index to a node with a higher index. That is, every directed edge has the form (v_i, v_j) with i < j.
- Every node other than v_n has at least one outgoing edge.
Given an ordered graph G, we want to find the longest path from v_1 to v_n.
Consider the following greedy algorithm.
Show that this algorithm does not correctly solve the problem, by giving an example of an ordered graph for which it does not return the correct answer. Be sure to explain what the correct answer is and what incorrect answer is returned by the algorithm.w \gets v_1L \gets 0\mathsf {while} w \neq v_n:Choose the outgoing edge (w, v_j) with the smallest jw \gets v_jIncrement L\mathsf {return} L- Describe an efficient algorithm that takes an ordered graph G and returns the length of the longest path from v_1 to v_n. Justify its correctness and analyze its time complexity.
Hint.
- October 27, 2026
If you know the length of the longest path from v_j to v_n for every j > i, can you figure out the length of the longest path from v_i to v_n?
[DP6] Closest subset without going over (3 pts) [00R3]
- November 2, 2026
This problem is similar to one we did in class, but slightly more general. Suppose we have a set \{x_1, x_2, \dots , x_n\} of n positive integers, and a target sum S, which is a positive integer. In class, we considered finding a subset of \{x_1, \dots , x_n\} whose sum is exactly equal to S. Instead, let’s now consider finding a subset whose sum is as close to S as possible without going over; that is, the subset with the largest possible sum \leq S. For example, given the set \{1,2,7,12\} and the target sum 18, there is no subset which sums exactly to 18, but the one which comes closest without going over is \{12,2,1\} which sums to 15. Note that \{12,7\}, with a sum of 19, is closer to the target in an absolute sense, but it is greater than the target; we are interested in the biggest sum which is \leq the target.
- Describe a simple brute-force algorithm for solving this problem. What is the running time of the algorithm?
- Using dynamic programming, describe an algorithm with running time \Theta (nS). Be sure that you explain how to find not only the maximum possible sum, but also the actual subset which has that sum. Justify the correctness of your algorithm.
- This is known as a psuedopolynomial-time algorithm: the running time is a polynomial in the value of S, but actually exponential in terms of the size of the input (i.e. the number of bits needed to represent S). Give one example of a set of inputs for which your dynamic programming solution would be faster, and one example of a set of inputs for which the brute force algorithm would be faster.
[DP7] Making change (3 pts) [00R4]
- November 2, 2026
Consider the problem of making change for C cents using the fewest possible number of coins. Assume that each coin’s value is an integer.
- Describe a greedy algorithm to make change for C cents using US quarters, dimes, nickels, and pennies. (It turns out that the greedy algorithm is actually optimal for US coins (and most real-world coin systems), though coming up with a proof of this fact is nontrivial.)
- Give a set of coin denominations for which the greedy algorithm does not yield an optimal solution. Your set should include a penny so that there is a solution for every value of C.
- Design and analyze an algorithm to make change using the fewest number of coins that works for any set of coins. That is, as input your algorithm should take:
- n, the number of different coin types;
- a list c_1, c_2, …, c_n giving the values of the different coins (you may assume they are already sorted from smallest to largest); and
- the number of cents C we would like to make change for.
As output your algorithm should either report that it is not possible to make the required amount C using the given coins, or give a multiset (i.e. a set that allows duplicate elements) of coins which add up to C such that the number of coins in the multiset is as small as possible. For example, if given as input c_1 = 1, c_2 = 5, c_3 = 20 and the target value C = 47, your algorithm should output \{20, 20, 5, 1, 1\}. Note that we assume there is an unlimited supply of coins of each type. Be sure to justify your algorithm’s correctness and analyze its time complexity.
Max flow problems [00S6]
- November 11, 2026
In class, we saw that the Ford-Fulkerson algorithm can be implemented to run in O(CE) time, where C is the total capacity coming out of the source vertex. There is also a particular instantiation of the Ford-Fulkerson framework, known as Dinitz’ Algorithm, which can be implemented to find maximum flows in a network in O(V^2 E) time. For these problems, you may assume O(CE) or O(V^2 E) as the time needed to solve a max flow problem, whichever is better.
[F1] Mobile connections (2 pts) [00S7]
- November 11, 2026
Consider a set of mobile computing clients in a certain town who each need to be connected to one of several possible base stations. We’ll suppose there are n clients, with the position of each client specified by its (x,y) coordinates in the plane. There are also k base stations; the position of each of these is specified by (x,y) coordinates as well.
We wish to connect each client to exactly one of the base stations, but our choice of connections is constrained in the following ways. First, there is a range parameter, denoted by r: a client can only be connected to a base station that is within distance r. There is also a load parameter L: no more than L clients can be connected to any single base station.
Your goal is to design a polynomial-time algorithm for the following problem. Given the positions of a set of clients and a set of base stations, as well as the range and load parameters r and L, decide whether every client can be connected simultaneously to a base station, subject to the constraints r and L.
Be sure to justify the correctness of your algorithm and analyze its asymptotic running time. Also, be sure to express the running time in terms of n, k, L, and r as appropriate; do not just say it takes O(V^2 E).
[F2] Exam scheduling (2 pts) [00S8]
- November 11, 2026
Given a list of n classes, a list of r rooms, a list of t time slots, and a list of a therapy animals, our goal is to assign the final exam for each class to a particular room at a particular time, with a visit from one of a list of therapy animals.
- Each class i has a size S_i.
- Each room j has a capacity C_j; classes may only be assigned to rooms that are large enough to fit them, that is, if S_i \leq C_j.
- Each room is only available during some of the time slots, and may have at most one class assigned to it per time slot.
- Each therapy animal is only available during certain time slots, and an animal may only visit one exam per time slot.
- To avoid overwhelming the therapy animals, each animal may be assigned to visit a maximum of three exams.
Design an algorithm to find a valid way to assign each class to a room, time, and therapy animal that satisfies all the constraints (or report that no such assignment is possible). Be sure to justify the correctness of your algorithm and analyze its asymptotic running time.
[F3] Vertex capacities (2 pts) [00S9]
- November 11, 2026
Suppose that, in addition to edge capacities, a flow network has vertex capacities. That is, each vertex v has a limit c(v) on how much flow can pass through v. Show how to transform a flow network G = (V,E) with vertex capacities into an equivalent flow network G' = (V', E') without vertex capacities, such that a maximum flow in G' has the same value as a maximum flow in G. How many vertices and edges does G' have?
[F4] Escape problem (3 pts) [00SA]
- November 11, 2026
An n \times n grid is an undirected graph consisting of n rows and n columns of vertices, as shown in the figure below. We denote the vertex in the ith row and the jth column by (i,j). All vertices in a grid have exactly four neighbors, except for the boundary vertices.
Given m \leq n^2 starting points (x_1, y_1), (x_2, y_2), \dots , (x_m, y_m) in the grid, the escape problem is to determine whether or not there are m vertex-disjoint paths (i.e. paths that do not share any vertices or edges) from the starting points to any m different points on the boundary. For example, the grid shown on the left has an escape, but the grid on the right does not.
Describe a polynomial-time algorithm to solve the escape problem, and analyze its running time.
Hint.
- November 11, 2026
Use the result from [F3] Vertex capacities (2 pts).
Amortized Analysis problems [00T7]
- November 18, 2026
Amortization practice [00T8]
- November 18, 2026
These questions are courtesy of Jeff Erickson.
Suppose we are maintaining a data structure under a series of n operations. Let f(k) denote the actual running time of the kth operation. For each of the following functions f, determine the resulting amortized cost of a single operation. For amortized costs other than \Theta (1), be sure to argue why your cost is also a lower bound, i.e. why it is not possible to do any better. Hints:
- Start by either making tables of values and looking for patterns, and/or trying to write down a mathematical expression for the total cost f(1) + f(2) + \dots + f(n).
- If you notice a pattern, you could try proving it using the accounting method.
- Alternatively, if you are able to write down a mathematical expression for an upper bound on the total cost and simplify it, divide by n to get the amortized cost of a single operation.
[A1] Ruler function (1 pt)
- November 18, 2026
f(k) is the largest integer i such that k is evenly divisible by 2^i.
[A2] Powers of two (1 pt)
- November 18, 2026
f(k) = k if k is a power of 2, and f(k) = 1 otherwise.
[A3] Fibonacci numbers (1 pt)
- November 18, 2026
f(k) = k if k is a Fibonacci number, and f(k) = 1 otherwise.
[A4] Squares (1 pt)
- November 18, 2026
f(k) = k if k is a perfect square, and f(k) = 1 otherwise.
[A5] Doubly-extensible array (2 pts) [00T9]
- November 18, 2026
This question is also courtesy of Jeff Erickson.
A doubly extensible array is a data structure that stores a sequence of items and supports the following operations:
- \mathsf {AddToFront}(x) adds x to the beginning of the sequence.
- \mathsf {AddToEnd}(x) adds x to the end of the sequence.
- \mathsf {Lookup}(k) returns the kth item in the sequence (0-indexed), or \mathsf {Null} if the current length of the sequence is less than or equal to k.
Describe and analyze a simple data structure that implements a doubly extensible array. Your \mathsf {AddToFront} and \mathsf {AddToBack} algorithms should take O(1) amortized time, and your \mathsf {Lookup} algorithm should take O(1) worst-case time. The data structure should use O(n) space, where n is the current length of the sequence.
Hint.
- November 18, 2026
Use two arrays.
[A6] Queue from Two Stacks (2 pts) [00TA]
- November 19, 2026
Describe how to implement a queue using two stacks and O(1) additional memory, so that the amortized time for any enqueue or dequeue operation is O(1). The only access you have to the stacks is through the standard methods \mathsf {Push}, \mathsf {Pop}, and \mathsf {IsEmpty}; in particular you should not assume anything about how the stacks are implemented. You may assume that \mathsf {Push}, \mathsf {Pop}, and \mathsf {IsEmpty} take O(1) time in the worst case.
[A7] Fits (3 pts) [00TB]
- November 19, 2026
Suppose that instead of powers of two, we represent integers as a sum of distinct Fibonacci numbers. In other words, instead of an array of bits, we keep an array of fits (fibonacci digits), where each fit is either 0 or 1, and the i^{th} least significant fit indicates whether the sum includes the i^{th} Fibonacci number F_{i}. For example, the fit-string 101110_{F} represents the number F_6+F_4+F_3+F_2=8+3+2+1=14. Design and analyze an algorithm to increment a fit-string in \Theta (1) amortized time, assuming that a fit-string counter starts at 0 and is repeatedly incremented. As with the example above, assume that F_{1}=F_{2}=1, that the array of fits is indexed starting from 1, and that the i^{th} index of the array stores the i^{th} fit. Also observe that unlike binary, a given number n does not necessarily have a unique representation as a fit-string; it does not matter which representations are generated by your algorithm.
NP-completeness problems [00W5]
- December 2, 2026
[NP1] IND-SET-FIND (3 pts) [00W6]
- December 2, 2026
In class we argued why IND-SET-OPT \leq _P IND-SET: we can do binary search, calling a black box to solve IND-SET only \Theta (\lg n) times, to zero in on the maximum size of an independent set.
Consider the variant problem IND-SET-FIND, which, given a graph G as input, returns as output an actual subset of vertices of G which are a maximum-size independent set. Prove that IND-SET-FIND \leq _P IND-SET-OPT.
[NP2] \mathsf {Resource Reservation} (4 pts) [00W7]
- December 2, 2026
Suppose you’re consulting for a group that manages a high-performance real-time system in which asynchronous processes make use of shared resources. Thus the system has a set of n processes and a set of m resources. Each process specifies a set of resources that it requests to use. Each resource might be requested by many processes; but it can only be used by a single process. Your job is to allocate resources to processes that request them. If a process is allocated all the resources it requests, then it is active; otherwise it is blocked. You want to perform the allocation so that as many processes as possible are active. Thus we phrase the \mathsf {Resource Reservation} problem as follows: Given a set of processes and resources, the set of requested resources for each process, and a number k, is it possible to allocate resources to processes so that at least k processes will be active?
Consider the following list of problems. For each problem either give a polynomial-time algorithm or prove that the problem is NP-complete.
- The general \mathsf {Resource Reservation} problem defined above.
Hint.
- December 2, 2026
Show IND-SET \leq _P \mathsf {Resource Reservation}.
- The special case of the problem when k = 2.
- The special case of the problem when there are two types of resources—say, people and equipment—and each process requires at most one resource of each type. (In other words, each process requires at most one specific person and one specific piece of equipment.)
- The special case of the problem when each resource is requested by at most two processes.
[NP3] Subset sum (1 pt) [00W8]
- December 3, 2026
The \mathsf {Subset Sum} problem asks, given as inputs a set of integers \{x_1, \dots , x_n\} and a target sum S, is there a subset of the x_i whose sum is exactly S? It turns out that this problem is NP-complete. On an activity in class, you actually wrote a dynamic programming algorithm to solve this problem. Explain why you do not win $1 million.
[NP4] HITTING-SET (3 pts) [00W9]
- December 3, 2026
Consider a set A = \{a_1, \dots , a_n\} and a collection B_1, B_2, \dots , B_m of subsets of A (i.e., B_i \subseteq A for each i).
We say that a set H \subseteq A is a hitting set for the collection B_1, B_2, \dots , B_m if H contains at least one element from each B_i—that is, if H \cap B_i is not empty for each i (so H “hits” all the sets B_i).
Problem HITTING-SET [00WA]
- December 3, 2026
We now define the HITTING-SET problem as follows. We are given a set A = \{a_1, \dots , a_n\}, a collection B_1, B_2, \dots , B_m of subsets of A, and a number k. We are asked: Is there a hitting set H \subseteq A for B_1, B_2, \dots , B_m whose size is at most k?
Prove that HITTING-SET is NP-complete.
Hint.
- December 3, 2026
Try proving a polynomial-time reduction from VERTEX-COVER.
[NP5] Monotone Satisfiability with Few True Variables (3 pts) [00WB]
- December 3, 2026
Consider an instance of the SAT problem, specified by clauses C_1, \dots , C_k over a set of Boolean variables x_1, \dots , x_n. We say that the instance is monotone if each term in each clause consists of a nonnegated variable; that is, each term is equal to x_i, for some i, rather than \overline {x_i}. Monotone instances of SAT are very easy to solve: they are always satisfiable, by setting each variable equal to 1.
For example, suppose we have the three clauses (x_1 \lor x_2), (x_1 \lor x_3), (x_2 \lor x_3). This is monotone, and indeed the assignment that sets all three variables to 1 satisfies all the clauses. But we can observe that this is not the only satisfying assignment: we could also have set x_1 and x_2 to 1, and x_3 to 0. Indeed, for any monotone instance, it is natural to ask how few variables we must set to 1 in order to satisfy it.
Given a monotone instance of SAT, together with a number k, the Monotone Satisfiability with Few True Variables (MSFTV) problem asks: is there a satisfying assignment for the instance in which at most k variables are set to 1? Prove that this problem is NP-complete.
Hint.
- December 3, 2026
Try reducing from HITTING-SET.