Optional · after the core sequence

Choose one deeper question.

Networks, repeated subproblems, and the limits of exact algorithms. These topics extend the supplied beginner notes; they do not add weeks, deadlines or required submissions.

← Return to Week 14

Graphs and routes

Lectures 10–14 · optional extension

Model the network before choosing the algorithm

A graph has vertices for things and edges for relationships. A factory map might use junctions as vertices and traversable aisles as edges. Decide whether travel is directed and whether the weight represents distance, time or energy. A graph model can be wrong even when the algorithm is implemented correctly.

An adjacency matrix uses space proportional to n²; adjacency lists use space proportional to n + m, where n is the number of vertices and m the number of edges. Lists are often convenient for sparse networks. A matrix provides direct edge lookup but also stores the absent connections.

Explore with a queue or a stack

Breadth-first search (BFS) uses a queue. It discovers vertices in increasing numbers of edges from the start, so its parent pointers give shortest paths when every edge has the same cost. Depth-first search (DFS) follows one branch deeply before returning, using a stack or recursion. Both take O(n + m) with adjacency lists, but DFS does not generally find shortest paths.

For a disconnected network, restart at an undiscovered vertex to find every component. A two-colouring attempt gives neighbours opposite colours; an edge whose ends have the same colour exposes a conflict. With directed dependencies, a back edge during DFS signals a cycle. Reversing DFS finishing order gives a topological order only when the directed graph is acyclic. Low-link methods extend DFS to articulation vertices or strongly connected components; they need more state than a visited flag.

Connecting everything is different from finding a route

A minimum spanning tree (MST) connects all vertices of a connected undirected weighted graph with minimum total edge weight. Prim grows a tree using a cheapest crossing edge. Kruskal considers edges in increasing weight order and uses union-find to reject cycles. An MST minimises the cost of the network, not the distance of every journey through it.

Dijkstra finds shortest paths from one source with nonnegative edge weights. Each relaxation asks whether a route through the current vertex improves a stored distance. With adjacency lists and a binary heap, its cost is O((n + m) log n). Negative edges invalidate its settled-distance argument. For all pairs, Floyd–Warshall considers each possible intermediate vertex: D[i,j] = min(D[i,j], D[i,k] + D[k,j]), taking Θ(n³). Negative cycles require separate detection and make some shortest distances unbounded below.

Trace one small network

Graph W: undirected edges A–B (4), A–C (1), B–C (2), B–D (5), C–D (8), D–E (3), C–E (10). Draw it on paper. Run a shortest-path trace from A, then compare the purpose of that result with a minimum spanning tree.

Engineering question: Are you minimising the wiring installed, a robot’s travel time, or the number of junctions crossed? Those are three different objectives.

Practice questions

20 test questions · 37 written questions · 57 total

Each question is followed by its answer and explanation. Hard questions also include a starting hint and smaller reasoning steps.

Test questions

Choose one option. Cost questions state their model and whether the bound is tight, expected or worst-case. Here lg means log₂, and heap positions start at 1.

Question 1 · easy

The maximum number of edges in a simple undirected graph on 5 vertices is:

  1. 5
  2. 10
  3. 20
  4. 25

Answer: option B. n(n − 1)/2 = 5 × 4 / 2.

Question 2 · easy

An undirected graph has 7 edges. The degrees of its vertices add up to:

  1. 7
  2. 14
  3. 21
  4. it depends on the graph

Answer: option B. Every edge is counted once at each of its two endpoints.

Question 3 · easy

For an n-vertex graph, what is the tightest listed worst-case space bound for a full adjacency matrix?

  1. O(n + m)
  2. O(n²)
  3. O(m)
  4. O(n log n)

Answer: option B. One entry per pair of vertices, edge or not.

Question 4 · easy

Breadth-first search keeps its discovered-but-unprocessed vertices in:

  1. a stack
  2. a queue
  3. a heap
  4. a hash table

Answer: option B. First found, first processed, which is why it expands by distance.

Question 5 · easy

Shortest paths in an unweighted graph are found by:

  1. BFS
  2. DFS
  3. Prim’s algorithm
  4. Kruskal’s algorithm

Answer: option A. The BFS tree path to each vertex uses the fewest possible edges.

Question 6 · easy

A tree with 12 vertices has how many edges?

  1. 11
  2. 12
  3. 13
  4. 66

Answer: option A. Always n − 1.

Question 7 · easy

A triangle (three mutually adjacent vertices) is:

  1. bipartite
  2. not bipartite
  3. a DAG
  4. a tree

Answer: option B. It is an odd cycle, and two colours cannot colour it.

Question 8 · easy

A directed graph has a topological sort if and only if it is:

  1. connected
  2. acyclic
  3. complete
  4. bipartite

Answer: option B. A cycle can never be laid out left to right.

Question 9 · easy

What edge-weight condition ensures the standard settled-once Dijkstra algorithm is correct for every input satisfying it?

  1. all weights equal
  2. no negative weights
  3. a DAG
  4. a tree

Answer: option B. Negative edges break the “nearest unknown vertex is settled” step.

Question 10 · easy

Floyd’s all-pairs algorithm runs in:

  1. Θ(n²)
  2. Θ(n³)
  3. Θ(n log n)
  4. Θ(m)

Answer: option B. Three nested loops over the vertices.

Question 11 · medium

A graph has edges 1–2, 1–3, 2–4, 3–4, 4–5. BFS from 1, taking neighbours in increasing order, discovers vertices in the order:

  1. 1, 2, 4, 3, 5
  2. 1, 2, 3, 4, 5
  3. 1, 3, 2, 4, 5
  4. 1, 2, 3, 5, 4

Answer: option B. Distance 1 vertices (2, 3) before distance 2 (4) before distance 3 (5).

Question 12 · medium

On the undirected graph with edges 1–2, 1–3, 2–4, 3–4, 4–5, run recursive DFS from 1, visiting neighbours in increasing order. What is the discovery order?

  1. 1, 2, 4, 3, 5
  2. 1, 2, 3, 4, 5
  3. 1, 3, 4, 2, 5
  4. 1, 2, 4, 5, 3

Answer: option A. From 4 the smallest undiscovered neighbour is 3, so 3 comes before 5.

Question 13 · medium

The weight of the minimum spanning tree of graph W is:

Graph W is undirected: A–B (4), A–C (1), B–C (2), B–D (5), C–D (8), D–E (3), C–E (10). Parenthesised numbers are edge weights.

  1. 10
  2. 11
  3. 12
  4. 14

Answer: option B. Edges A–C (1), B–C (2), D–E (3) and B–D (5).

Question 14 · medium

Running Dijkstra’s algorithm on graph W from A, the distance to D is:

Graph W is undirected: A–B (4), A–C (1), B–C (2), B–D (5), C–D (8), D–E (3), C–E (10). Parenthesised numbers are edge weights.

  1. 5
  2. 8
  3. 9
  4. 11

Answer: option B. A–C–B–D costs 1 + 2 + 5, cheaper than A–C–D at 9.

Question 15 · medium

Running Kruskal’s algorithm on graph W, the first edge REJECTED is:

Graph W is undirected: A–B (4), A–C (1), B–C (2), B–D (5), C–D (8), D–E (3), C–E (10). Parenthesised numbers are edge weights.

  1. A–B
  2. B–D
  3. C–D
  4. D–E

Answer: option A. After A–C, B–C and D–E are accepted, A–B (weight 4) would close the cycle A–C–B.

Question 16 · medium

In recursive DFS of a simple undirected graph, classify each undirected edge once. Every non-tree edge connects a descendant to an ancestor, so it is a:

  1. back edges only
  2. forward edges only
  3. cross edges only
  4. any of the three kinds

Answer: option A. DFS explores an entire active branch before finishing it. A non-tree edge therefore joins a descendant to an ancestor. The reverse direction is the same undirected edge, not a separate forward edge.

Question 17 · medium

For the DAG with edges 1→2, 1→3, 2→4, 3→4, which is a valid topological order?

  1. 2, 1, 3, 4
  2. 1, 3, 4, 2
  3. 1, 3, 2, 4
  4. 4, 3, 2, 1

Answer: option C. In (a) 2 precedes 1, in (b) 4 precedes 2, and (d) is fully reversed.

Question 18 · medium

The articulation vertices of the path 1–2–3–4–5 are:

  1. 1 and 5
  2. 2, 3 and 4
  3. 3 only
  4. none

Answer: option B. Removing any interior vertex disconnects the path; removing an endpoint does not.

Question 19 · hard

Use settled-once Dijkstra, which never changes a settled distance, on A→B (2), A→C (5), C→B (−4). It reports distance to B as ___, but the true shortest distance is ___.

  1. 2 and 1
  2. 1 and 1
  3. 2 and 2
  4. 5 and 1

In simpler words: Trace the vertex that is settled too early.

Starting hint: Compare direct A→B with the later route through C.

Answer: option A. B is settled at 2 as the nearest vertex and never revisited, but A→C→B costs 1.

Step by step
  1. After A, tentative distances are B=2 and C=5. Settled-once Dijkstra freezes B at 2.
  2. The route A→C→B costs 5−4=1. A later negative edge improved a supposedly final distance.

Question 20 · hard

Which statement is FALSE?

  1. a connected undirected graph with distinct edge weights has a unique minimum spanning tree
  2. every minimum spanning tree contains a shortest path between every pair of vertices
  3. BFS tree paths from their root are shortest paths in an unweighted graph
  4. a simple undirected graph is bipartite exactly when it has no odd cycle

In simpler words: Compare the cheapest whole network with the cheapest single journey.

Starting hint: Use a triangle with weights 2,2,3.

Answer: option B. Triangle A–B (2), B–C (2), A–C (3): the MST path from A to C costs 4 while the direct edge costs 3.

Step by step
  1. The MST selects the two weight-2 edges, total 4.
  2. Between the end vertices, the direct weight-3 edge is a shorter path. Minimising total network weight does not preserve every shortest journey.

Written questions

Read each question together with its explanation, trace or proof. Numbering continues from the test questions.

Question 21 · easy

Define the degree of a vertex, a path, and a connected graph.

Answer & reasoning

For a simple undirected graph, degree is the number of incident edges. A path is a vertex sequence whose consecutive vertices are joined by edges; a simple path has no repeated vertices. A graph is connected when every pair of vertices is joined by a path.

Question 22 · easy

What is the maximum number of edges in a simple undirected graph on n vertices? In a simple directed graph (no self-loops)?

Answer & reasoning

n(n − 1)/2, one per unordered pair; n(n − 1), one per ordered pair.

Question 23 · easy

In an undirected graph, what do the degrees of all vertices add up to?

Answer & reasoning

2m, because every edge contributes 1 to the degree of each of its two endpoints.

Question 24 · easy

A graph has edges 1–2, 1–3, 2–4, 3–4, 4–5. Run BFS from vertex 1, taking neighbours in increasing order. In what order are vertices discovered, and what is the distance from 1 to 5?

Answer & reasoning

1, 2, 3, 4, 5. Vertex 5 is at distance 3 (for example 1–2–4–5).

Question 25 · easy

Same graph, DFS from vertex 1 with neighbours in increasing order. In what order are vertices discovered?

Use the undirected graph with edges 1–2, 1–3, 2–4, 3–4, 4–5; visit neighbours in increasing order.

Answer & reasoning

1, 2, 4, 3, 5: from 1 go to 2, from 2 to 4, from 4 to 3 (its smallest undiscovered neighbour), 3 has nothing new, back to 4, then 5.

Question 26 · easy

A graph on vertices 1 to 6 has edges 1–2, 2–3 and 4–5. How many connected components does it have?

Answer & reasoning

three: {1, 2, 3}, {4, 5} and {6}. An isolated vertex is a component on its own.

Question 27 · easy

How many edges does a tree with n vertices have? What happens if you add one more edge between two of its vertices?

Answer & reasoning

n − 1; the new edge closes exactly one cycle, since the tree already contains one path between its endpoints.

Question 28 · easy

Which traversal finds shortest paths in an unweighted graph, and why does the other one not?

Answer & reasoning

BFS, because it discovers vertices in order of increasing distance from the start. DFS dives deep first and may reach a vertex by a long roundabout route before a short one.

Question 29 · easy

Is a triangle bipartite? Is a 4-cycle (a square)?

Answer & reasoning

the triangle is not: three mutually adjacent vertices cannot be two-coloured. The square is: colour opposite corners alike.

Question 30 · easy

List every topological sort of the DAG with edges A→B, B→C and A→C.

Answer & reasoning

only A, B, C. A must come before B and C, and B before C.

Question 31 · easy

What is the weight of the minimum spanning tree of a triangle whose edges weigh 1, 2 and 3?

Answer & reasoning

3, using the edges of weight 1 and 2. A spanning tree of three vertices has exactly two edges.

Question 32 · easy

What condition on edge weights does Dijkstra’s algorithm require?

Answer & reasoning

no negative weights. The course assumes all weights are positive.

Question 33 · easy

Match each algorithm with its running time from the notes: Prim (simple implementation), Kruskal with union-find, Dijkstra with a heap, Floyd.

Answer & reasoning

Simple array-based Prim: O(n²). Kruskal: O(m log m) for sorting the edges, with near-linear union-find work. Dijkstra with adjacency lists and a binary heap: O((n + m) log n), often written O(m log n) when all n vertices are reachable and m ≥ n−1. Floyd–Warshall: Θ(n³).

Question 34 · easy

What is a DAG, and what kind of vertex must every DAG contain?

Answer & reasoning

A DAG is a directed graph with no directed cycle. Every nonempty finite DAG has a vertex with in-degree zero: otherwise repeatedly follow an incoming edge backwards; finiteness forces a repeated vertex and hence a directed cycle.

Question 35 · medium

Run Prim’s algorithm on graph W starting from A. Give the order in which edges are added and the total weight.

Answer & reasoning

A–C (1), then C–B (2), then B–D (5) (cheaper than C–D at 8 and C–E at 10), then D–E (3). Total 1 + 2 + 5 + 3 = 11.

Question 36 · medium

Run Kruskal’s algorithm on graph W. List the edges in the order considered and say which are accepted or rejected.

Answer & reasoning

A–C (1) accepted; B–C (2) accepted; D–E (3) accepted; A–B (4) rejected, it would close the cycle A–C–B; B–D (5) accepted, joining {A, B, C} to {D, E}; four edges are now in, so C–D (8) and C–E (10) are not needed. Total 11, the same tree as Prim’s.

Question 37 · medium

Run Dijkstra’s algorithm on graph W from A. Give the final distance to every vertex and the shortest-path tree.

Answer & reasoning

Distances from A are A = 0, C = 1, B = 3, D = 8, E = 11. A–C–B costs 3, improving the direct edge of weight 4. A–C–B–D costs 8. E has two equally short routes: A–C–E and A–C–B–D–E, both 11. One shortest-path tree uses A–C, C–B, B–D, C–E; choosing D–E instead is also valid. Parent choices depend on the tie rule; strict-improvement-only updates keep C as E’s parent.

Question 38 · medium

Does a minimum spanning tree always contain the shortest path between every pair of vertices? Prove or give a counterexample.

Answer & reasoning

no. Triangle A–B (2), B–C (2), A–C (3): the MST is A–B, B–C with weight 4. The shortest path from A to C in the graph is the direct edge of weight 3, but in the tree the path A–B–C has weight 4.

Question 39 · medium

Give a small directed graph with one negative edge on which Dijkstra’s algorithm returns a wrong distance, and explain what goes wrong.

Answer & reasoning

A→B (2), A→C (5), C→B (−4). Dijkstra settles B at distance 2 as the nearest unknown vertex and never revisits it, but A→C→B costs 5 − 4 = 1. The greedy step assumes that adding edges can never make a path shorter, which negative weights violate.

Question 40 · medium

Run the DFS-based topological sort on the DAG with edges 1→2, 1→3, 2→4, 3→4, 4→5, 3→5, starting from 1 and exploring neighbours in increasing order. Give the finishing order and the resulting topological order.

Answer & reasoning

1 → 2 → 4 → 5; 5 finishes, 4 finishes, 2 finishes; back at 1, go to 3; its neighbours 4 and 5 are done, so 3 finishes; then 1. Finishing order 5, 4, 2, 3, 1; reversed: 1, 3, 2, 4, 5. Check: every edge points left to right.

Question 41 · medium

Run the in-degree-zero-removal method on the same DAG, with the queue processed in increasing order.

Use the DAG with edges 1→2, 1→3, 2→4, 3→4, 4→5, 3→5.

Answer & reasoning

in-degrees are 1:0, 2:1, 3:1, 4:2, 5:2. Output 1, reducing 2 and 3 to zero. Output 2 (4 drops to 1), output 3 (4 drops to 0, 5 to 1), output 4 (5 drops to 0), output 5. Order 1, 2, 3, 4, 5, also valid; a DAG may have several topological sorts.

Question 42 · medium

How do you test whether a directed graph contains a cycle? Give two methods.

Answer & reasoning

run DFS and watch for a back edge (an edge to a vertex that is discovered but not yet finished); or run the in-degree removal method and check whether fewer than n vertices come out.

Question 43 · medium

Count the number of distinct paths from s to t in a DAG in O(n + m).

Answer & reasoning

Initialise paths[s] = 1 and the other counts to zero. Process a topological ordering; for each edge v→w, add paths[v] to paths[w]. Dependencies are complete when a vertex is processed. This uses O(n + m) arithmetic operations. Path counts can be exponentially large, so arbitrary-precision bit costs are not necessarily constant per addition.

Question 44 · medium

Which vertices are articulation vertices in the path 1–2–3–4? In the cycle 1–2–3–4–1?

Answer & reasoning

in the path, 2 and 3 (removing either disconnects it); the endpoints are not. In the cycle, none: removing any single vertex leaves a path, still connected.

Question 45 · medium

The diameter of a graph is the largest shortest-path distance between any two vertices. How would you compute it for an unweighted graph, and at what cost?

Answer & reasoning

For a connected unweighted graph, run BFS from every vertex and take the largest distance: O(n(n + m)). For a disconnected graph, state a convention: the diameter over all vertex pairs is infinite if unreachable pairs have infinite distance, or report separate component diameters.

Question 46 · medium

Run Floyd’s algorithm on the directed graph with w(1, 2) = 4, w(1, 3) = 11, w(2, 3) = 2. Show what changes at each k.

Answer & reasoning

start with D[1,2] = 4, D[1,3] = 11, D[2,3] = 2, zeros on the diagonal, ∞ elsewhere. k = 1: no entry improves (nothing leads into 1). k = 2: D[1,3] = min(11, D[1,2] + D[2,3]) = min(11, 6) = 6. k = 3: no change (nothing leaves 3). Final shortest distance from 1 to 3 is 6.

Question 47 · medium

Two-colour the graph with edges 1–2, 2–3, 3–4, 4–1 and 1–3 using BFS from vertex 1. Is it bipartite?

Answer & reasoning

colour 1 white; its neighbours 2, 4 and 3 become black; then the edge 2–3 joins two black vertices. Not bipartite: 1–2–3 is a triangle, an odd cycle.

Question 48 · medium

Process the edges (1, 2), (3, 4), (2, 3), (5, 6), (1, 4) with union-find, in that order. What are the sets after each step, and which edge would Kruskal reject?

Answer & reasoning

{1,2} {3} {4} {5} {6}; then {1,2} {3,4} {5} {6}; then {1,2,3,4} {5} {6}; then {1,2,3,4} {5,6}; finally (1, 4): find(1) = find(4) already, so nothing merges; Kruskal would reject this edge as cycle-forming.

Question 49 · medium

Given a directed graph in adjacency-list form, compute the in-degree of every vertex in O(n + m).

Answer & reasoning

set in[v] = 0 for all v, then walk every adjacency list once and, for each edge x→y encountered, add 1 to in[y]. Each edge is seen exactly once.

Question 50 · hard

Prove that in a depth-first search of an undirected graph every non-tree edge is a back edge, so there are no forward or cross edges.

In simpler words: Explain why an undirected DFS edge cannot jump between finished branches.

Starting hint: DFS examines every neighbour before finishing a vertex.

Answer & reasoning
Step by step
  1. Let x be discovered before y, with edge {x,y}.
  2. If y is still undiscovered when this edge is examined, DFS descends toward y before finishing x.
  3. Thus the two endpoints lie on an ancestor–descendant chain. A non-tree edge is viewed upward as a back edge; its reverse is not a second edge.

For an undirected edge {x,y}, suppose x is discovered first. DFS cannot finish x while y remains undiscovered, because it examines every neighbour before finishing; that edge would discover y. Thus y is discovered while x is active and lies in its DFS subtree. Every undirected edge therefore connects ancestor and descendant. If it is not the discovery edge, classify it as a back edge when viewed from descendant toward ancestor. The reverse view is the same undirected edge, not a separate forward edge.

Question 51 · hard

Prove that the path from the root to any vertex in a BFS tree is a shortest path.

In simpler words: Explain why a BFS parent chain uses the fewest edges.

Starting hint: Think of the queue as distance layers 0,1,2,… .

Answer & reasoning
Step by step
  1. The start is layer 0. Its newly discovered neighbours form layer 1.
  2. All layer-d vertices leave the queue before any layer-(d+1) vertex is processed.
  3. A vertex first reached from layer d cannot have a shorter undiscovered route: that route’s earlier layer would already have found it. Its parent chain therefore has shortest length d+1.

claim: BFS discovers all vertices at distance d before any vertex at distance d + 1, and a vertex at distance d + 1 is always discovered from a vertex at distance d. Induction on d: the root is the only vertex at distance 0. Assume the claim up to d. Every vertex at distance d + 1 has a neighbour at distance d; the queue holds all distance-d vertices before any at distance d + 1, so when those are processed each distance-(d + 1) vertex is discovered from a distance-d parent and put in the queue before any distance-(d + 2) vertex. Hence parent pointers step down by exactly one distance unit, and the tree path from the root to v has exactly dist(v) edges.

Question 52 · hard

Prove that a graph is bipartite if and only if it contains no cycle of odd length.

In simpler words: Connect two-colouring with even and odd cycles.

Starting hint: Prove both directions separately.

Answer & reasoning
Step by step
  1. If an edge always changes colour, a cycle returns to its starting colour only after an even number of edges.
  2. Conversely, colour BFS levels alternately in each component.
  3. An edge within the same level would create an odd cycle: take the two tree branches from their last common ancestor, then that edge. With no odd cycle, every edge joins opposite colours.

if it is bipartite, colours alternate along any cycle, so returning to the start colour needs an even number of steps. Conversely, if there is no odd cycle, BFS from a vertex in each component and colour vertices by the parity of their distance. Any edge joins vertices whose distances differ by at most 1; if an edge joined two vertices at the same distance d, the two tree paths to them plus that edge would form a closed walk of length 2d + 1, which contains an odd cycle. So every edge joins different parities: a valid two-colouring.

Question 53 · hard

Prove that if all edge weights in a connected graph are distinct, the minimum spanning tree is unique.

In simpler words: Show that two different cheapest trees cannot coexist with distinct weights.

Starting hint: Exchange one carefully chosen edge between the two trees.

Answer & reasoning
Step by step
  1. Choose the lightest edge e that appears in exactly one proposed MST, say T₁.
  2. Adding e to T₂ creates a cycle. That cycle contains an edge f outside T₁; otherwise T₁ would contain a cycle too.
  3. Because weights are distinct and e was lightest among differing edges, f is heavier. Replacing f by e makes T₂ cheaper, a contradiction.

suppose T₁ ≠ T₂ are both minimum. Let e be the lightest edge that is in one of them but not both, say e ∈ T₁ \ T₂. Adding e to T₂ closes a cycle, which must contain an edge f not in T₁ (otherwise T₁ would contain a cycle). f is in T₂ but not T₁, and since e was the lightest such edge and weights are distinct, w(f) > w(e). Then T₂ − f + e is a spanning tree lighter than T₂, contradicting minimality.

Question 54 · hard

Show that a minimum spanning tree also minimises the heaviest edge among all spanning trees.

In simpler words: Show that an MST also makes its largest edge as small as possible.

Starting hint: Remove a largest MST edge and look at the two resulting parts.

Answer & reasoning
Step by step
  1. Call that edge weight B. Suppose another spanning tree uses only edges lighter than B.
  2. That other tree must cross the cut between the two parts using some edge f of weight below B.
  3. Substitute f for the removed edge: the original MST would become cheaper. The contradiction proves no spanning tree has a smaller bottleneck.

suppose some spanning tree S has maximum edge weight w less than the MST’s maximum edge weight, and let e be an MST edge with w(e) > w. Removing e splits the MST into two parts; S is connected, so it contains an edge f crossing between those parts with w(f) ≤ w < w(e). Then MST − e + f is a lighter spanning tree, contradicting minimality. (Kruskal’s order makes this vivid: it never adds an edge heavier than necessary to connect.)

Question 55 · hard

Give an O(n + m) algorithm for single-source shortest paths on a DAG, even when some edge weights are negative.

In simpler words: Find shortest paths by processing a DAG in dependency order.

Starting hint: A topological order puts every edge’s start before its end.

Answer & reasoning
Step by step
  1. Set the source distance to 0 and the others to infinity.
  2. At each reachable vertex u, try dist[u]+w(u,v) for every outgoing edge and keep improvements.
  3. All possible predecessors are already processed, so a negative edge causes no late return. Visit each vertex and edge once: O(n+m) word operations.

compute a topological order (O(n + m)). Set dist[s] = 0 and all others to ∞. Process vertices in topological order, and for each edge v→w set dist[w] = min(dist[w], dist[v] + w(v, w)). Every path to w passes through vertices earlier in the order, so dist[v] is final before it is used. Negative weights are harmless because a DAG has no cycles to loop around.

Question 56 · hard

You are given a graph and its minimum spanning tree T. Describe how to find the second-best spanning tree (the lightest spanning tree different from T), and give a running time.

In simpler words: Find the cheapest tree that differs from a given MST.

Starting hint: Add one unused edge, then remove an edge from its newly formed cycle.

Answer & reasoning
Step by step
  1. Each non-tree edge e creates exactly one cycle with T.
  2. Remove a heaviest edge on that cycle to get the cheapest tree obtainable with this e. Record its weight, even if tied with T.
  3. Try every non-tree edge and keep the best. A standard tree-exchange argument guarantees a best alternative among these swaps. Finding each tree path by a scan costs O(n), for O(nm) overall.

Assume a connected graph and seek the lightest spanning tree different from the given MST T; it may have equal weight. There exists a best alternative obtainable by one swap. For each non-tree edge e, find the unique tree path between its endpoints, remove a maximum-weight edge f on that path, and evaluate T − f + e. Keep the cheapest alternative. Scanning each path takes O(n), giving O(nm). If there is no non-tree edge, no alternative spanning tree exists. “Strictly heavier second-best” is a different problem when weights tie.

Question 57 · hard

Prove by induction that every tree with n vertices has exactly n − 1 edges.

In simpler words: Remove one leaf, use the smaller tree, then add the leaf back.

Starting hint: A finite tree with at least two vertices has a leaf.

Answer & reasoning
Step by step
  1. For one vertex there are zero edges, matching n−1.
  2. Remove a leaf and its single incident edge. Remaining vertices still form a tree.
  3. By induction that smaller tree has n−2 edges. Restoring one edge gives n−1.

base case n = 1: no edges. For n ≥ 2, a tree has a leaf (a vertex of degree 1): start anywhere and keep walking along unused edges; you cannot revisit a vertex because there are no cycles, so the walk ends at a vertex with no other edge, a leaf. Remove that leaf and its edge; the rest is still connected and acyclic, so it is a tree with n − 1 vertices and, by the hypothesis, n − 2 edges. Adding the leaf’s edge back gives n − 1.

Search and dynamic programming

Lectures 15–18 · optional extension

Search systematically and reject impossible branches

Backtracking builds a solution one choice at a time. A solution test recognises a complete valid answer; a candidate generator proposes the next choices; a processing step records a finished answer. Undo a choice before trying its alternative. Pruning rejects a partial solution only when no completion of that partial solution can work.

For Sudoku, candidates are values missing from the cell’s row, column and box. Choosing the cell with the fewest candidates often exposes contradictions sooner. The search can still be expensive: pruning improves particular instances without proving a polynomial bound.

Reuse answers to repeated subproblems

Naive Fibonacci recursion repeatedly asks for the same smaller values. Memoisation caches each computed answer; bottom-up dynamic programming fills a table in dependency order. Both reduce the number of subproblem evaluations. Counting operations on arbitrarily large integers still requires attention to bit length.

The design questions are: What does one state mean? Which smaller states determine it? What are the base cases? In what order can the states be evaluated? For coin values 1, 3 and 4, let best[a] be the fewest coins for amount a. Set best[0] = 0 and minimise 1 + best[a−coin] over coins that fit. The greedy choice 4 for amount 6 misses the better pair 3 + 3.

Strings and ordered work

Edit distance uses the cost of transforming one prefix into another. The final edit is a substitution or match, an insertion, or a deletion. Initialise distances to the empty string by the prefix lengths, then fill each cell from the three neighbouring predecessor states. Save decisions if you need the actual edit sequence, rather than just its cost.

For nonnegative task durations in a fixed order, linear partitioning chooses contiguous ranges to minimise the largest range sum. The last cut separates an already-solved prefix from a final range: minimise the maximum of those two costs over possible cuts. State whether empty ranges are allowed. Similar “choose the last decision” reasoning helps with string cuts, weighted scheduling and egg-dropping strategies.

The state must contain the information that matters

The best continuation must depend only on the state you stored. A route through cities needs to remember which cities were already visited; recording only the current city loses essential information. A travelling-salesman DP can use a visited subset and final city, but there are exponentially many subsets. Dynamic programming avoids repeated work; it does not automatically make the number of distinct states small.

Engineering question: Before caching a planning result, identify what may change: position, battery level, visited tasks or remaining capacity. An incomplete cache key can reuse an answer to the wrong problem.

Practice questions

20 test questions · 36 written questions · 56 total

Each question is followed by its answer and explanation. Hard questions also include a starting hint and smaller reasoning steps.

Test questions

Choose one option. Cost questions state their model and whether the bound is tight, expected or worst-case. Here lg means log₂, and heap positions start at 1.

Question 1 · easy

Backtracking is essentially:

  1. breadth-first search over configurations
  2. depth-first search over partial solutions
  3. a sorting technique
  4. a hashing technique

Answer: option B. Extend a partial solution when you can, back up when you cannot.

Question 2 · easy

A set of 6 elements has how many subsets?

  1. 6
  2. 36
  3. 64
  4. 720

Answer: option C. 2⁶: each element is in or out.

Question 3 · easy

The number of permutations of 5 items is:

  1. 25
  2. 32
  3. 120
  4. 5

Answer: option C. 5! = 5 × 4 × 3 × 2 × 1.

Question 4 · easy

In the generic backtracking template used here, which routine excludes impossible next choices before recursion?

  1. is_a_solution
  2. construct_candidates
  3. process_solution
  4. the main program

Answer: option B. Candidates that cannot lead to a solution are simply never offered.

Question 5 · easy

F(12), the twelfth Fibonacci number with F(0) = 0 and F(1) = 1, is:

  1. 89
  2. 144
  3. 233
  4. 120

Answer: option B. F(10) = 55, F(11) = 89, F(12) = 144.

Question 6 · easy

The naive recursive Fibonacci function has running time that is:

  1. linear
  2. quadratic
  3. exponential
  4. logarithmic

Answer: option C. The number of calls grows as Θ(φⁿ), where φ = (1 + √5)/2 ≈ 1.618, because the same subproblems are recomputed. This counts calls rather than arbitrary-precision arithmetic cost.

Question 7 · easy

C(6, 2), the number of ways to choose 2 items from 6, is:

  1. 12
  2. 15
  3. 20
  4. 30

Answer: option B. 6 × 5 / 2, or Pascal’s rule C(5, 1) + C(5, 2) = 5 + 10.

Question 8 · easy

With insertion, deletion and substitution each costing 1, what is the Levenshtein edit distance between “flaw” and “lawn”?

  1. 1
  2. 2
  3. 3
  4. 4

Answer: option B. Delete the f, insert the n.

Question 9 · easy

The length of the longest common subsequence of ABC and BCA is:

  1. 1
  2. 2
  3. 3
  4. 0

Answer: option B. BC appears in order in both; no three letters do.

Question 10 · easy

Why do many dynamic programs on two strings use only polynomially many states?

  1. the characters can be freely rearranged
  2. a state can use two prefix lengths, giving (m + 1)(n + 1) pairs
  3. randomness removes all repeated work
  4. a hash table makes every state unnecessary

Answer: option B. There are only (m + 1)(n + 1) pairs of prefix lengths. This is a useful property of these string problems, not a claim that dynamic programming works only on strings or always has polynomially many states.

Question 11 · medium

With coins of value 1, 5 and 6, the fewest coins that make 10 is:

  1. 2
  2. 3
  3. 4
  4. 5

Answer: option A. 5 + 5. The greedy rule (6 + 1 + 1 + 1 + 1) uses five.

Question 12 · medium

A knapsack holds weight 5. Items (weight, value) are (2, 3), (3, 4), (4, 5), each usable at most once. The best total value is:

  1. 5
  2. 7
  3. 8
  4. 12

Answer: option B. The items of weight 2 and 3 fit exactly and are worth 3 + 4.

Question 13 · medium

The number of ways to climb 6 stairs taking 1 or 2 steps at a time is:

  1. 8
  2. 13
  3. 21
  4. 12

Answer: option B. ways(n) = ways(n − 1) + ways(n − 2): 1, 2, 3, 5, 8, 13.

Question 14 · medium

Split 2, 8, 3, 4, 6, in that order, into two nonempty contiguous ranges. Minimise the larger sum. What is the optimum?

  1. 10
  2. 12
  3. 13
  4. 17

Answer: option C. {2, 8} and {3, 4, 6} give 10 and 13; every other cut has a range of at least 13.

Question 15 · medium

What is the length of a strictly increasing subsequence of maximum length in 3, 1, 4, 1, 5, 9, 2, 6?

  1. 3
  2. 4
  3. 5
  4. 6

Answer: option B. For example 3, 4, 5, 6 or 1, 4, 5, 9; no five elements increase.

Question 16 · medium

What is the maximum sum of a nonempty contiguous stretch of [2, −5, 3, 4, −1, 2]?

  1. 7
  2. 8
  3. 9
  4. 10

Answer: option B. 3 + 4 − 1 + 2 = 8, found by best[i] = max(a[i], best[i − 1] + a[i]).

Question 17 · medium

With only 1 egg and an 8-floor building, the number of drops needed in the worst case to find the critical floor is:

  1. 3
  2. 4
  3. 8
  4. 1

Answer: option C. You cannot risk breaking the only egg, so you must test floors 1, 2, 3, … in order.

Question 18 · medium

Which running time is pseudo-polynomial because it depends on a binary-encoded target value T rather than its bit length?

  1. edit distance in O(|s|·|t|)
  2. subset sum in O(nT)
  3. LCS of explicit strings in O(|s|·|t|)
  4. Floyd–Warshall on an explicit n-vertex graph in O(n³)

Answer: option B. T is a number in the input; its value can be exponential in its number of digits.

Question 19 · hard

The number of derangements of 5 items (permutations with no item in its own position) is:

  1. 24
  2. 44
  3. 120
  4. 76

In simpler words: Count permutations that move every item.

Starting hint: Use D(n)=(n−1)(D(n−1)+D(n−2)).

Answer: option B. D(n) = (n − 1)(D(n − 1) + D(n − 2)): D(1) = 0, D(2) = 1, D(3) = 2, D(4) = 9, D(5) = 44.

Step by step
  1. Item 1 has n−1 possible new positions. If its partner moves back to position 1, derange the remaining n−2 items; otherwise contracting that link leaves a derangement problem on n−1 items. This gives (n−1)(D(n−2)+D(n−1)).
  2. D(1)=0 and D(2)=1 give D(3)=2 and D(4)=9. For three items, the two possibilities are 231 and 312.
  3. Then D(5)=4(9+2)=44. A derangement moves every item, not merely some items.

Question 20 · hard

Dynamic programming solves TSP in O(n² 2ⁿ) because its state records:

  1. a prefix of the cities in a fixed order
  2. the set of cities visited so far and the current city
  3. only the current city
  4. a complete permutation of the cities

In simpler words: Count the information a TSP subproblem must remember.

Starting hint: Current city alone cannot tell which cities remain.

Answer: option B. There are 2ⁿ subsets times n current cities, each state costing O(n) to fill.

Step by step
  1. There are at most 2ⁿ visited sets and n current cities.
  2. Trying at most n transitions per state gives O(n²2ⁿ). Memoisation avoids repeats but cannot remove the exponential number of sets.

Written questions

Read each question together with its explanation, trace or proof. Numbering continues from the test questions.

Question 21 · easy

Name the three problem-specific routines that the generic backtrack procedure needs, and say what each does.

Answer & reasoning

is_a_solution (are the first k choices a complete answer?), construct_candidates (which values may go in position k, given positions 1 to k − 1?), process_solution (print, count or use a finished solution).

Question 22 · easy

How many subsets does a set of 4 elements have? How many permutations?

Answer & reasoning

2⁴ = 16 subsets and 4! = 24 permutations.

Question 23 · easy

What is pruning, and in which routine of the backtracking code does it live?

Answer & reasoning

refusing to extend a partial solution that can no longer lead to a complete one, so whole branches of the search tree are never entered. It lives in construct_candidates, which simply does not offer doomed candidates.

Question 24 · easy

In the n-queens search, why does the program examine at most n! boards rather than all ways of putting n queens on n² squares?

Answer & reasoning

no two queens can share a row or a column, so the solution is a permutation: row i’s queen sits in column aᵢ, all columns different. That leaves n! arrangements, and diagonal checks prune most of those too.

Question 25 · easy

Compute F(10) by filling a table from F(0) = 0 and F(1) = 1.

Answer & reasoning

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55; F(10) = 55.

Question 26 · easy

Why does the plain recursive Fibonacci function take exponential time?

Answer & reasoning

The recurrence recomputes the same subproblems many times. Its call count satisfies C(n) = 1 + C(n−1) + C(n−2), so C(n) = 2F(n+1) − 1 = Θ(φⁿ), where φ ≈ 1.618. Saying “about 1.6ⁿ” is informal; 1.6 is not the exact asymptotic base.

Question 27 · easy

In one sentence each, what is memoisation and what is bottom-up dynamic programming?

Answer & reasoning

memoisation keeps the recursive structure but caches each result the first time it is computed; bottom-up DP replaces recursion with loops that fill the table from the smallest cases upward.

Question 28 · easy

Use Pascal’s rule to compute C(5, 2) from smaller coefficients.

Answer & reasoning

C(5, 2) = C(4, 1) + C(4, 2) = 4 + 6 = 10.

Question 29 · easy

What is the edit distance between “cat” and “cut”? Between “cat” and “cats”? Between “kitten” and “sitting”?

Answer & reasoning

1 (substitute a → u); 1 (insert s); 3 (k → s, e → i, insert g).

Question 30 · easy

What is the length of the longest common subsequence of ABCD and ACBD? Give one such subsequence.

Answer & reasoning

3; for example ABD (or ACD).

Question 31 · easy

What is the length of the longest increasing subsequence of 5, 1, 6, 2, 7? Give an example.

Answer & reasoning

3; for example 5, 6, 7 or 1, 2, 7.

Question 32 · easy

Split {1, 2, 3, 4, 5}, in this order, into 2 contiguous ranges so that the larger range sum is as small as possible. What is that sum?

Answer & reasoning

The four nonempty cuts after positions 1, 2, 3 and 4 give maximum sums 14, 12, 9 and 10. The minimum is 9, achieved by {1, 2, 3} | {4, 5}. A cut before the first element would create an empty range and is not included.

Question 33 · easy

State the principle of optimality in one sentence and give one algorithm from the notes that relies on it.

Answer & reasoning

Once the state contains all information that can affect future choices, an optimal solution can use optimal subproblem solutions. In edit distance the state is a pair of prefix lengths; for shortest paths, a shortest route has shortest subroutes. This principle alone does not justify Dijkstra’s settled-once order, which also needs nonnegative edges.

Question 34 · medium

A derangement is a permutation in which no element stays in its own position. How many derangements of {1, 2, 3, 4} are there, and how would you prune a backtracking search to generate them?

Answer & reasoning

9 (for example 2143, 2341, 2413, 3142, 3412, 3421, 4123, 4312, 4321). Prune by never offering i as a candidate for position i, so no wasted branches are entered.

Question 35 · medium

With coins of value 1, 3 and 4, make change for 6 using the fewest coins. Compare the greedy rule (always take the largest coin that fits) with dynamic programming.

Answer & reasoning

greedy takes 4, then 1, then 1: three coins. DP with best[a] = 1 + min(best[a − 1], best[a − 3], best[a − 4]) gives best[6] = 2 (3 + 3). Greedy fails; the DP considers every last coin.

Question 36 · medium

Fill in the edit-distance table for turning “sun” into “snow”, and read off the distance and an edit sequence.

Answer & reasoning

rows for the prefixes of “sun” against columns for the prefixes of “snow”: row 0: 0 1 2 3 4; row s: 1 0 1 2 3; row u: 2 1 1 2 3; row n: 3 2 1 2 3. Distance 3: keep s, substitute u → n, substitute n → o, insert w.

Question 37 · medium

Find the longest common subsequence of AGGTAB and GXTXAYB.

Answer & reasoning

GTAB, of length 4. (The table’s bottom-right entry is 4; tracing back the matches gives G, T, A, B.)

Question 38 · medium

Items have (weight, value) (1, 1), (3, 4), (4, 5), (5, 7) and the knapsack holds weight 7. Each item may be taken at most once. What is the best total value, and what DP recurrence solves it?

Answer & reasoning

9, taking the items of weight 3 and 4. Let V[i, w] be the best value using the first i items within weight w: V[i, w] = max(V[i − 1, w], V[i − 1, w − wᵢ] + vᵢ) when wᵢ ≤ w, else V[i − 1, w]; the table has (n + 1)(W + 1) cells.

Question 39 · medium

You leave mile 0 with a full tank; the car goes 60 miles on a tank. Stations are at miles 40, 70, 120 and 150, and the destination is at mile 190. What is the minimum number of fill-ups, and where?

Answer & reasoning

4, at 40, 70, 120 and 150. From 0 the only reachable station is 40; from 40, only 70 (120 is 80 miles away); from 70, only 120; from 120, only 150; from 150 the destination is 40 miles away. The recurrence G[i] = 1 + min over reachable j of G[j] gives the same count; here the “drive as far as you can” greedy also works because fill-ups are all equal in cost.

Question 40 · medium

A 10-character string must be broken after positions 2 and 5; breaking a string of length L costs L. What is the cheapest order and its cost?

Answer & reasoning

break at 5 first (cost 10), leaving a piece of length 5 that is then broken at 2 (cost 5): total 15. Breaking at 2 first costs 10 + 8 = 18. The DP C[i, j] = (j − i) + min over breaks k of C[i, k] + C[k, j] computes 15.

Question 41 · medium

Build Pascal’s triangle down to row 6 and read off C(6, 3).

Answer & reasoning

rows 1; 1 1; 1 2 1; 1 3 3 1; 1 4 6 4 1; 1 5 10 10 5 1; 1 6 15 20 15 6 1. So C(6, 3) = 20.

Question 42 · medium

Are there solutions to the n-queens problem for n = 2 and n = 3? How many for n = 4?

Answer & reasoning

none for n = 2 or 3 (every placement leaves two queens attacking). For n = 4 there are 2 solutions, mirror images: columns (2, 4, 1, 3) and (3, 1, 4, 2).

Question 43 · medium

You climb a staircase of n steps taking 1 or 2 steps at a time. Write a recurrence for the number of distinct ways and compute it for n = 5.

Answer & reasoning

ways(n) = ways(n − 1) + ways(n − 2), with ways(1) = 1, ways(2) = 2 (the last move was a 1-step or a 2-step). ways(3) = 3, ways(4) = 5, ways(5) = 8: the Fibonacci numbers.

Question 44 · medium

Find the maximum sum of a contiguous stretch of the array [−2, 1, −3, 4, −1, 2, 1, −5, 4] using a one-pass DP.

Answer & reasoning

let best[i] be the best sum of a stretch ending at position i: best[i] = max(a[i], best[i − 1] + a[i]). The values are −2, 1, −2, 4, 3, 5, 6, 1, 5, and the answer is the maximum, 6, from the stretch 4, −1, 2, 1.

Question 45 · medium

Find the length of the longest palindromic subsequence of “character”, and say how to compute it with a tool from the notes.

Answer & reasoning

The length is 5; “carac” is a palindromic subsequence of “character”. An LCS computation against the reverse gives the correct optimal length, but an arbitrary reconstructed LCS need not itself be a palindrome. To recover a palindrome reliably, use interval DP: L[i,j] = 2 + L[i+1,j−1] when the endpoint characters match, otherwise max(L[i+1,j], L[i,j−1]); base cases are 0 for an empty interval and 1 for a single character.

Question 46 · medium

Why is filling the edit-distance table row by row, left to right, a valid evaluation order? Name one other valid order.

Answer & reasoning

cell (i, j) needs (i − 1, j − 1), (i, j − 1) and (i − 1, j), all of which lie in an earlier row or earlier in the same row. Column by column, top to bottom, works for the same reason; so does going along anti-diagonals.

Question 47 · hard

Prove that the naive recursive Fibonacci function makes at least F(n) calls when computing F(n).

In simpler words: Compare the number of recursive calls with the Fibonacci value.

Starting hint: Count the current call as well as its two recursive branches.

Answer & reasoning
Step by step
  1. Set C(0)=C(1)=1. For n≥2, C(n)=1+C(n−1)+C(n−2).
  2. Assuming C(n−1)≥F(n−1) and C(n−2)≥F(n−2), their sum already reaches F(n).
  3. The extra current call can only increase the count. Both base cases hold, so induction proves C(n)≥F(n), an exponential lower bound.

let C(n) be the number of calls. C(0) = C(1) = 1, and C(n) = 1 + C(n − 1) + C(n − 2) for n ≥ 2. Induction: C(0) ≥ F(0) and C(1) ≥ F(1); if C(n − 1) ≥ F(n − 1) and C(n − 2) ≥ F(n − 2), then C(n) ≥ F(n − 1) + F(n − 2) = F(n). Since F(n) ≈ 1.618ⁿ / √5, the number of calls is exponential.

Question 48 · hard

Give a DP for the longest path from s in a DAG, then explain why the same idea fails on a graph with cycles.

In simpler words: Change DAG shortest-path minimisation into maximisation.

Starting hint: Use minus infinity for an unreachable vertex so it cannot win a maximum.

Answer & reasoning
Step by step
  1. Set long[s]=0, all other values to −∞, and process topological order.
  2. For each reachable u, update long[v]=max(long[v],long[u]+w(u,v)).
  3. With cycles, a simple path must remember used vertices to avoid repetition. A state containing only the current vertex loses that information.

Initialise long[s] = 0 and every other value to −∞. In topological order, for every edge u→v from a reachable u, update long[v] = max(long[v], long[u] + w(u,v)). This takes O(n + m). In a cyclic graph, the longest simple path depends on which vertices have already been used, so the vertex alone is not a sufficient state. The longest-simple-path decision problem is NP-complete; the optimisation problem is NP-hard.

Question 49 · hard

Extend edit distance so that swapping two adjacent characters (“teh” → “the”) costs 1 instead of 2. Give the extra case in the recurrence.

In simpler words: Add a local case for swapping the last two characters.

Starting hint: Only use the new case when those characters match in reverse order.

Answer & reasoning
Step by step
  1. Suppose s ends in …ab and t ends in …ba at the prefixes being compared.
  2. Besides insertion, deletion and substitution, allow the cost for the prefixes two characters shorter, plus 1.
  3. This restricted recurrence gives optimal string alignment distance. It does not allow every combination of overlapping edits that unrestricted Damerau–Levenshtein permits.

For i,j ≥ 2, if s[i] = t[j−1] and s[i−1] = t[j], also consider D[i−2,j−2] + 1. Keep the usual insertion, deletion and substitution cases. This computes the restricted optimal-string-alignment distance, where a substring is not edited repeatedly. Fully unrestricted Damerau–Levenshtein distance requires more state; the extra local case alone does not compute it.

Question 50 · hard

Partition the sequence 3, 1, 4, 1, 5, 9, 2, 6 into 3 contiguous ranges minimising the largest range sum. Give the optimum and prove no better value exists.

In simpler words: Find a good split, then prove every smaller cap fails.

Starting hint: Test the cap 13 by packing each positive range as far right as possible.

Answer & reasoning
Step by step
  1. A cap of 14 works: [3,1,4,1] | [5,9] | [2,6], with sums 9,14,8.
  2. With cap 13, maximal packing gives [3,1,4,1] | [5] | [9,2] | [6]: four ranges.
  3. For positive entries, ending any earlier range sooner cannot improve how far the same number of ranges reaches. So three ranges cannot fit under 13, proving optimum 14.

The optimum is 14: 3,1,4,1 | 5,9 | 2,6 has sums 9,14,8. To rule out 13, greedily pack each range as far as possible under that cap: [3,1,4,1], [5], [9,2], [6]. Four ranges are needed. For positive entries, cutting an earlier range sooner cannot let any later range end farther right than this maximal packing, so three ranges cannot achieve cap 13. Hence 14 is optimal.

Question 51 · hard

You have 2 eggs and a 10-floor building. What is the minimum number of drops that always finds the critical floor, and what is the strategy?

In simpler words: Balance the number of remaining tests after an egg breaks.

Starting hint: With one egg left, you must test upwards one floor at a time.

Answer & reasoning
Step by step
  1. Try floors 4,7,9,10 while the first egg survives: the jumps are 4,3,2,1.
  2. If it breaks, search the skipped floors with the remaining egg. The worst branch still totals only four drops.
  3. With three drops, two eggs cover at most 3+2+1=6 floors. Four is therefore both sufficient and necessary for ten floors.

4. Drop from floor 4: if it breaks, test 1, 2, 3 one at a time with the last egg (up to 3 more drops). If not, drop from 7: if it breaks, test 5, 6; if not, drop from 9: if it breaks, test 8; if not, drop from 10. Each branch uses at most 4 drops. Three cannot suffice: with 3 drops and 2 eggs the most floors you can settle is 3 + 2 + 1 = 6. The recurrence E(k, n) = 1 + min over x of max(E(k − 1, x − 1), E(k, n − x)) gives E(2, 10) = 4.

Question 52 · hard

The travelling salesman problem satisfies the principle of optimality, yet dynamic programming does not make it polynomial. Explain exactly where the exponential comes from.

In simpler words: Count the states rather than assuming DP means polynomial.

Starting hint: Remember both the current city and the set already visited.

Answer & reasoning
Step by step
  1. A set of n cities has 2ⁿ subsets. The current city adds at most n possibilities.
  2. Each state considers at most n previous cities or next transitions, depending on the formulation.
  3. Multiplying gives O(n²2ⁿ). Reusing states beats enumerating n! tours, but there are still exponentially many states.

the state must record which cities have already been visited, because the best way to finish depends on it; that state is an arbitrary subset of the n cities, and there are 2ⁿ subsets. With n choices of current city the table has n · 2ⁿ entries, each costing O(n): O(n² 2ⁿ), much better than n! but still exponential. In string problems the corresponding state is a prefix, and there are only n of those.

Question 53 · hard

Greedy set cover repeatedly picks the subset covering the most still-uncovered elements. Give an instance where it does not find the smallest cover.

In simpler words: Make the largest first set leave two awkward uncovered elements.

Starting hint: Give those two elements different remaining sets.

Answer & reasoning
Step by step
  1. S₁ covers four elements, so greedy takes it first.
  2. Element 5 then requires S₂, and element 6 requires S₃: three sets total.
  3. But S₂∪S₃ already equals the whole universe. Two sets suffice, while no single listed set covers it.

U = {1, 2, 3, 4, 5, 6}, S₁ = {1, 2, 3, 4}, S₂ = {1, 2, 5}, S₃ = {3, 4, 6}. Greedy picks S₁ (4 new elements), then needs both S₂ and S₃ for 5 and 6: three sets. But S₂ and S₃ alone cover everything: two sets.

Question 54 · hard

Design the construct_candidates routine for a Sudoku solver, and suggest one ordering trick that prunes far more.

In simpler words: Avoid Sudoku choices already ruled out by a row, column or box.

Starting hint: A cell’s candidates are the missing digits from all three constraints.

Answer & reasoning
Step by step
  1. Collect the digits used in the cell’s row, column and 3×3 box.
  2. Offer only 1,…,9 minus that union. Zero candidates means this branch cannot succeed.
  3. Choose an empty cell with the fewest candidates next. This is a heuristic for finding conflicts early, not a guarantee of polynomial search.

for the next empty cell, the candidates are the digits 1 to 9 not already present in that cell’s row, column and 3 × 3 box; compute them by scanning those 20 neighbours. The trick: instead of filling cells in a fixed order, always choose next the empty cell with the fewest candidates (often just one), which forces contradictions to surface early and keeps the search tree narrow.

Question 55 · hard

Solve the weighted movie-star problem from exercise 30 (each job has a fee, maximise the total fee) with dynamic programming, and give its running time.

Each fixed-time job has a fee; choose nonoverlapping jobs to maximise total fee, rather than the number of jobs. Define compatibility consistently; adjacent jobs may share a boundary if their intervals are half-open.

In simpler words: For each job, compare taking it with skipping it.

Starting hint: Sort by finish time, then find the last compatible earlier job.

Answer & reasoning
Step by step
  1. Let p(i) be the last earlier job ending no later than job i starts; use half-open intervals.
  2. Skipping earns OPT(i−1). Taking earns feeᵢ+OPT(p(i)), because only that compatible prefix remains available.
  3. Set OPT(0)=0 and keep the larger amount. Sorting and binary-searching all predecessors cost O(n log n); filling the table costs O(n).

Sort jobs by finish time and let p(i) be the last earlier job compatible with job i, found by binary search. For half-open intervals, compatibility means finish ≤ start. Set OPT(0) = 0 and OPT(i) = max(OPT(i−1), feeᵢ + OPT(p(i))). The first branch skips the job; the second includes it and the best compatible prefix. Sorting and predecessor searches take O(n log n); the DP itself takes O(n).

Question 56 · hard

Give a DP that decides whether a set of n positive integers has a subset summing to exactly T, state its running time, and explain why this does not contradict the hardness of subset sum (Lecture 21).

In simpler words: Track which target sums can be reached using a prefix of the items.

Starting hint: For an item s, a sum t either skips s or comes from t−s.

Answer & reasoning
Step by step
  1. Initially only sum 0 is reachable with no items.
  2. Use can[i,t]=can[i−1,t] OR can[i−1,t−sᵢ], with the second branch allowed only if t≥sᵢ.
  3. There are (n+1)(T+1) cells. A target such as T=2ᵇ has only b+1 binary digits but needs roughly 2ᵇ columns. That is why O(nT) is pseudo-polynomial.

Let can[i,t] mean that a subset of the first i positive numbers sums to t. Set can[0,0] true and can[0,t] false for t > 0. Use can[i,t] = can[i−1,t] or (t ≥ sᵢ and can[i−1,t−sᵢ]). The table takes O(nT) time. This is polynomial in the numeric value T, not in its bit length log₂ T; binary-encoded inputs can make T exponentially large. This is pseudo-polynomial time.

Limits and reductions

Lectures 19–22 · optional extension

Specify a yes-or-no question

“Find the best tour” is an optimisation request. “Is there a tour of length at most K?” is its decision counterpart. P and NP are classes of decision problems: P has polynomial-time solution algorithms; NP has polynomial-size certificates of yes-answers verifiable in polynomial time. Checking a tour means checking its visits and total weight, not proving that it is the shortest.

Keep the reduction direction straight

A polynomial reduction A → B translates any instance of A into an instance of B while preserving its answer. A fast algorithm for B would therefore solve A. To show that B is NP-hard, reduce a known hard problem to B. To call B NP-complete, also establish membership in NP. Reducing B to a known hard problem does not prove B hard.

For example, a vertex cover touches every edge. Its complement is an independent set containing no edge. That complementary relationship translates one decision question into the other. Independent sets become cliques in the complement graph. The reduction preserves the required size as well as the yes-or-no answer.

Use a small gadget you can check

SAT asks for truth values satisfying every clause. A long clause can be replaced by smaller clauses using fresh variables; the fresh values must be chosen so the transformed formula is satisfiable exactly when the original is. Work through Exercise 185 before trusting a memorised transformation.

In the standard 3-SAT-to-vertex-cover construction, use two opposite literal vertices joined by an edge for each variable, and a triangle of occurrence vertices for each clause. Join each clause occurrence to its matching variable literal. A satisfying assignment selects one true literal per variable and two vertices per triangle; leave out a true clause occurrence, whose cross-edge is then covered from the variable side. The target size is n + 2c.

Subset-sum and partition connect numerical selection problems. A subset-sum table indexed by target T takes O(nT), which is not polynomial in the bit length of a binary-encoded T. Integer programming can encode SAT with 0/1 variables and linear clause constraints. Restriction and local replacement are useful proof techniques, but the target problem’s rules must remain exactly the rules you claim to analyse.

Make a practical choice without claiming impossibility

NP-completeness does not prove that every instance takes exponential time, nor that no polynomial algorithm exists. P versus NP remains unresolved. It tells us why a universal efficient exact method would be a major breakthrough. Small-instance backtracking, structural restrictions, approximation and heuristics are practical options with different guarantees.

Engineering question: State which concession a planner makes: a bounded instance size, a restricted graph, an approximation guarantee, or a heuristic with no optimality guarantee. Test whether the concession is acceptable for the actual machine.

Practice questions

20 test questions · 35 written questions · 55 total

Each question is followed by its answer and explanation. Hard questions also include a starting hint and smaller reasoning steps.

Test questions

Choose one option. Cost questions state their model and whether the bound is tight, expected or worst-case. Here lg means log₂, and heap positions start at 1.

Question 1 · easy

A polynomial-time reduction from problem A to problem B shows that:

  1. A is easy
  2. B is at least as hard as A
  3. A is at least as hard as B
  4. A and B are both in P

Answer: option B. A fast algorithm for B would give one for A, so if A is hard, B is too.

Question 2 · easy

A decision problem is in NP when every yes-instance has:

  1. no polynomial-time solution
  2. a known polynomial-time solving algorithm
  3. a polynomial-size certificate verifiable in polynomial time
  4. no algorithm at all

Answer: option C. NP requires efficiently checkable certificates for yes-instances. It includes P; being in NP does not mean a problem is known to be hard.

Question 3 · easy

Which decision problem is known to be NP-complete?

  1. nonnegative-weight shortest path of cost at most K
  2. existence of an Eulerian circuit
  3. existence of a vertex cover of size at most k
  4. satisfiability of a 2-CNF formula

Answer: option C. The other three are in P.

Question 4 · easy

The smallest vertex cover of a triangle has size:

  1. 1
  2. 2
  3. 3
  4. 0

Answer: option B. One vertex misses the opposite edge; any two vertices touch all three edges.

Question 5 · easy

The largest independent set of a 4-cycle has size:

  1. 1
  2. 2
  3. 3
  4. 4

Answer: option B. Two opposite corners; any three corners include an adjacent pair.

Question 6 · easy

The clause set {x}, {¬x, y}, {¬y} is:

  1. satisfiable with x = true, y = true
  2. satisfiable with x = false
  3. not satisfiable
  4. satisfiable only with y = false

Answer: option C. The first clause forces x true, the second then forces y true, and the third forbids it.

Question 7 · easy

The P versus NP question asks whether:

  1. every problem whose answers can be checked quickly can also be solved quickly
  2. sorting can be done in linear time
  3. every graph is a tree
  4. SAT is in NP

Answer: option A. It is the gap between verifying and finding.

Question 8 · easy

Skiena’s preferred source problem for targets about ordering or routing is:

  1. 3-SAT
  2. integer partition
  3. vertex cover
  4. Hamiltonian path

Answer: option D. Vertex cover is for selection, integer partition for large numbers, 3-SAT for everything else.

Question 9 · easy

If a single NP-complete problem were solved in polynomial time, then:

  1. nothing would follow
  2. P = NP
  3. P ≠ NP
  4. NP would be empty

Answer: option B. Every problem in NP reduces to it.

Question 10 · easy

Which listed decision problem has a known polynomial-time algorithm?

  1. Hamiltonian-cycle existence
  2. simple-path existence with at least k edges
  3. Eulerian-circuit existence
  4. 3-colourability

Answer: option C. Using every edge once is easy; visiting every vertex once is hard.

Question 11 · medium

The chain construction turns the clause {a, b, c, d} into:

  1. {a, b, c} and {d}
  2. {a, b, v} and {¬v, c, d}
  3. {a, b, v} and {v, c, d}
  4. {a, v} and {¬v, b} and {c, d}

Answer: option B. The new variable v links the two halves and cannot satisfy both clauses by itself.

Question 12 · medium

A graph on n vertices with a vertex cover of size k has an independent set of size:

  1. k
  2. n − k
  3. n
  4. k²

Answer: option B. The vertices outside a cover are pairwise non-adjacent.

Question 13 · medium

A clique in G corresponds, in the complement graph of G, to:

  1. a clique
  2. a vertex cover
  3. an independent set
  4. a spanning tree

Answer: option C. All-edges-present becomes no-edges-present when edges are complemented.

Question 14 · medium

In the standard reduction from 3-SAT to vertex cover, each variable gets an edge and each 3-literal clause gets a triangle. For n variables and c clauses, how many vertices are created?

  1. n + c vertices
  2. 2n + 3c vertices
  3. 3n + 2c vertices
  4. nc vertices

Answer: option B. Two per variable gadget, three per clause triangle.

Question 15 · medium

In the same construction (one edge per variable and one triangle per clause), with n variables and c clauses, what vertex-cover size bound is used?

  1. n + 2c
  2. 2n + c
  3. n + c
  4. 3c

Answer: option A. One vertex per variable edge plus two per triangle.

Question 16 · medium

In the incidence-digit reduction from vertex cover to subset sum described in the notes, what base prevents carries from edge columns?

  1. 2
  2. 3
  3. 4
  4. 10

Answer: option C. Base 4. Each edge column can receive two endpoint contributions and one filler contribution, totalling at most 3. Thus no edge column carries. The notes use “integer partition” for this target-sum variant; equal-partition is treated separately in question 119.

Question 17 · medium

To recover sorted order from a convex-hull algorithm that returns vertices in boundary order, map each distinct real number x to which point?

  1. (x, 0)
  2. (x, x)
  3. (x, x²)
  4. (x², x)

Answer: option C. Points on a parabola are all on the hull, in x order.

Question 18 · medium

“Does G contain a simple path with at least k edges?” is shown NP-complete by:

  1. local replacement
  2. restriction: k = n − 1 is Hamiltonian path
  3. reducing it to SAT
  4. dynamic programming

Answer: option B. Set k = n − 1 to obtain Hamiltonian path, which proves NP-hardness. Also verify a proposed simple path in polynomial time to establish membership in NP. Both are needed for NP-completeness.

Question 19 · hard

For positive labelled subset-sum items of total W > 0 and target 0 ≤ t ≤ W, which two extra labelled items give the equal-partition reduction?

  1. t
  2. W − t
  3. 2W − t and W + t
  4. W

In simpler words: Force a target sum inside one equal half.

Starting hint: Find the new total before deciding where the large items can go.

Answer: option C. Add 2W − t and W + t. The new total is 4W, so each half must sum to 2W. The extra items sum to 3W and cannot share a half; the half containing 2W − t therefore needs original items totalling t.

Step by step
  1. Total W+(2W−t)+(W+t)=4W, so each half is 2W.
  2. The large items sum to 3W and must be separated. The half containing 2W−t needs precisely t from the original items.

Question 20 · hard

Which statement is an established algorithmic guarantee?

  1. every unsatisfiable formula is known to have a polynomial-size certificate verifiable in polynomial time
  2. both endpoints of a maximal matching form a vertex cover of size at most twice the optimum
  3. the doubled-MST shortcut tour can have three times the optimum length in a complete metric graph
  4. a polynomial-time algorithm is known for general 3-colourability

In simpler words: Use a matching as a lower bound on any vertex cover.

Starting hint: No one vertex can cover two disjoint matching edges.

Answer: option B. A matching uses disjoint edges, so every cover needs at least one endpoint per matched edge. Selecting both gives at most twice optimum; maximality ensures every edge is covered. The doubled-MST guarantee is at most 2, and no general polynomial algorithm for 3-colourability is known. General short certificates for unsatisfiability are also not known.

Step by step
  1. For r disjoint edges, every cover needs at least r vertices.
  2. Taking both endpoints uses 2r. Maximality ensures no uncovered edge remains, so this is a valid cover with the factor-2 guarantee.

Written questions

Read each question together with its explanation, trace or proof. Numbering continues from the test questions.

Question 21 · easy

What is a reduction, and in which direction does hardness travel along it?

Answer & reasoning

a translation of every instance of problem A into an instance of problem B that preserves the yes/no answer, computable in polynomial time. If A is hard, then B is at least as hard (a fast B would give a fast A). Fast algorithms travel the other way, from B to A.

Question 22 · easy

Define P, NP and NP-complete, one sentence each.

Answer & reasoning

P: problems solvable in polynomial time. NP: problems for which a proposed yes-answer can be checked in polynomial time. NP-complete: problems in NP to which every problem in NP reduces, so they are the hardest problems in NP.

Question 23 · easy

Why is satisfiability in NP?

Answer & reasoning

given a proposed truth assignment, you can check every clause in time linear in the size of the formula.

Question 24 · easy

Give a satisfying assignment for the clauses {x, y}, {¬x, y}, {¬y, z}.

Answer & reasoning

y = true and z = true satisfy all three clauses whatever x is.

Question 25 · easy

Is the clause set {x}, {¬x} satisfiable? What about the single clause {x, ¬x}?

Answer & reasoning

no: x would have to be both true and false. Yes: one literal of {x, ¬x} is always true.

Question 26 · easy

Write the decision version of the shortest-path problem.

Answer & reasoning

given a weighted graph, two vertices s and t, and a number k, is there a path from s to t of total weight at most k?

Question 27 · easy

What is the size of the smallest vertex cover of the path 1–2–3–4? Give one.

Answer & reasoning

2, for example {2, 3}: it touches the edges 1–2, 2–3 and 3–4. One vertex cannot touch all three edges.

Question 28 · easy

What is the size of the largest independent set of the same path?

Use the path graph with vertices 1, 2, 3, 4 and edges 1–2, 2–3, 3–4.

Answer & reasoning

2, for example {1, 3}, {1, 4} or {2, 4}. This is 4 − 2, the complement of a minimum vertex cover.

Question 29 · easy

What is the largest clique in a triangle? In the path 1–2–3–4?

Answer & reasoning

3 (the whole triangle); 2 (any single edge; no three vertices are mutually adjacent).

Question 30 · easy

In each pair, which problem is NP-complete: shortest path or longest simple path; Eulerian circuit or Hamiltonian circuit; edge cover or vertex cover?

Answer & reasoning

The decision versions of longest simple path, Hamiltonian circuit and vertex cover are NP-complete. Unweighted or nonnegative-weight shortest-path decision, Eulerian-circuit existence, and edge-cover decision have polynomial algorithms. Keep the input assumptions and decision/optimisation distinction explicit.

Question 31 · easy

Which of 2-SAT and 3-SAT has a fast algorithm, and why does the chain construction not settle the other?

Answer & reasoning

2-SAT is in P. The chain construction for proving hardness needs a spare slot in each clause to hold a linking variable, and clauses of size 2 have none, so it does not apply; 3-SAT is NP-complete.

Question 32 · easy

What does the question “P = NP?” ask, in plain words?

Answer & reasoning

whether every problem whose answers can be checked quickly can also be solved quickly. Nobody knows; it is the biggest open problem in computer science.

Question 33 · easy

Which four problems does Skiena use as sources for reductions, and what kind of target problem suits each?

Answer & reasoning

3-SAT (the general-purpose choice), integer partition (targets whose hardness involves large numbers), vertex cover (graph problems about selecting a subset), Hamiltonian path (graph problems about ordering or routing).

Question 34 · easy

If someone found a polynomial-time algorithm for vertex cover, what would follow?

Answer & reasoning

P = NP: every problem in NP reduces to vertex cover in polynomial time, so all of them, including SAT, TSP and the rest, would have polynomial algorithms.

Question 35 · medium

Convert the 4-literal clause {a, b, c, d} into clauses of exactly three literals using the chain construction, and check that the new clauses are satisfiable exactly when the old one is.

Answer & reasoning

Introduce v and use (a ∨ b ∨ v) ∧ (¬v ∨ c ∨ d). If a or b is true, choose v = false: the first clause is already satisfied and ¬v satisfies the second. Otherwise, if c or d is true, choose v = true: v satisfies the first and c or d satisfies the second. If all four original literals are false, the two clauses require v and ¬v simultaneously. Thus the new formula is satisfiable exactly when the original clause is.

Question 36 · medium

Convert the single-literal clause {a} into 3-literal clauses.

Answer & reasoning

with new variables v₁, v₂: {a, v₁, v₂}, {a, v₁, ¬v₂}, {a, ¬v₁, v₂}, {a, ¬v₁, ¬v₂}. Every combination of v₁, v₂ falsifies the other two literals of one clause, so only a = true satisfies all four.

Question 37 · medium

Prove that a graph on n vertices has a vertex cover of size k if and only if it has an independent set of size n − k.

Answer & reasoning

if S is a vertex cover, no edge has both endpoints outside S (such an edge would be uncovered), so V − S is independent. If I is independent, every edge has at most one endpoint in I, hence at least one in V − I, so V − I is a cover. The sizes are complementary.

Question 38 · medium

Describe the complement of the 4-cycle 1–2–3–4–1, and show how an independent set in the cycle becomes a clique in the complement.

Answer & reasoning

the complement has exactly the missing edges, 1–3 and 2–4. The independent set {1, 3} of the cycle is an edge, that is a clique of size 2, in the complement; likewise {2, 4}.

Question 39 · medium

Show that subset sum and the TSP decision problem are both in NP.

Answer & reasoning

subset sum: the certificate is the subset; add it up and compare with t, polynomial time. TSP: the certificate is the tour; check it visits every city once and add its edge weights, polynomial time.

Question 40 · medium

You want to prove that your problem X is NP-complete. Why is a reduction from X to SAT useless for that purpose, and what would it prove instead?

Answer & reasoning

A polynomial reduction X → SAT gives a method for solving X using a SAT solver; it establishes membership in NP for an ordinary polynomial many-one reduction to SAT, not NP-hardness of X. To prove X NP-hard, reduce a known NP-complete problem to X. To conclude NP-completeness, also establish that X is in NP. A SAT solver is not assumed to take exponential time on every input.

Question 41 · medium

Show that “does G contain a simple path with at least k edges?” is NP-complete, using restriction.

Answer & reasoning

the special case k = n − 1 asks whether G has a path through all n vertices, which is exactly the Hamiltonian path problem, known to be NP-complete. A problem with an NP-complete special case is NP-complete (membership in NP: the path is a checkable certificate).

Question 42 · medium

Write the integer-programming constraints that encode the clause (x ∨ ¬y ∨ z) in the reduction from SAT.

Answer & reasoning

Use integer variables X, X̄, Y, Ȳ, Z, Z̄ in {0,1}. Require X + X̄ = Y + Ȳ = Z + Z̄ = 1 and X + Ȳ + Z ≥ 1. The last inequality says at least one literal is true. Integrality is essential: allowing arbitrary fractions in [0,1] would not encode Boolean truth values.

Question 43 · medium

Someone hands you a graph and a colouring of its vertices with three colours. How quickly can you check whether it is a proper colouring, and what does that say about the 3-colouring problem?

Answer & reasoning

Check that every vertex is assigned one of the three allowed colours, then check each edge has differently coloured endpoints: O(n + m). This puts the decision problem in NP. Deciding whether such a colouring exists is NP-complete; finding a colouring is the associated search task.

Question 44 · medium

Explain why every problem in P is also in NP.

Answer & reasoning

if you can solve the problem in polynomial time, you can check any proposed answer in polynomial time simply by ignoring it, solving from scratch, and comparing.

Question 45 · medium

Give a polynomial reduction from “independent set of size ≥ k” to “clique of size ≥ k”.

Answer & reasoning

build the complement graph Ḡ (same vertices, an edge exactly where G has none), which takes O(n²), and ask for a clique of size k in Ḡ. A set is independent in G if and only if it is a clique in Ḡ.

Question 46 · medium

Show that set cover is NP-complete by a reduction from vertex cover.

Answer & reasoning

let the universe be the set of edges of G, and for each vertex v make the subset Sᵥ of edges touching v. A collection of k subsets covers all edges exactly when the corresponding k vertices form a vertex cover. Set cover is in NP (a proposed collection is easy to check), so it is NP-complete.

Question 47 · medium

Using the travelling salesman problem, explain the difference between verifying a solution and finding one.

Answer & reasoning

A proposed tour is checked by verifying the visits and adding its edge weights, then comparing with the bound; this takes polynomial time in the encoded input. Finding a qualifying tour requires an algorithm to select one. Exhaustive enumeration is one method, but is not known to be necessary. No polynomial-time exact algorithm for general TSP is known; that is not a proof that every method must enumerate all tours.

Question 48 · medium

Prove: if any single NP-complete problem is in P, then P = NP.

Answer & reasoning

let X be NP-complete and in P. Every problem Y in NP reduces to X in polynomial time. To solve Y: translate the instance to X (polynomial), solve X (polynomial), return the answer. Two polynomials compose to a polynomial, so Y is in P. Hence NP ⊆ P, and with P ⊆ NP always, P = NP. Equally, proving that one NP-complete problem needs exponential time would prove P ≠ NP.

Question 49 · hard

The partition problem asks whether a set of integers can be split into two halves with equal sums. Prove it is NP-complete by reducing subset sum to it.

In simpler words: Turn a target-sum question into an equal-halves question.

Starting hint: Create two large items that must go into different halves.

Answer & reasoning
Step by step
  1. Original total W plus new weights 2W−t and W+t gives total 4W; each half must weigh 2W.
  2. The two new weights together are 3W, so they cannot share a half.
  3. The half containing 2W−t needs exactly t from the original items. This proves both directions, and the numbers have polynomial bit length. Finally, checking a proposed partition is polynomial, giving NP membership.

Use positive-integer subset sum with total W > 0 and 0 ≤ t ≤ W; targets outside the range can be handled directly. Add two labelled items of weights 2W − t and W + t. The total is 4W, so equal halves each weigh 2W. The new items cannot share a half because together they weigh 3W > 2W. The half containing 2W − t needs original items totalling exactly t. Conversely such a subset determines a partition. Labels preserve distinct items even when weights coincide. The transformation has polynomial bit length; a proposed partition is easy to verify.

Question 50 · hard

Prove that Hamiltonian cycle is NP-complete by reducing Hamiltonian path to it.

In simpler words: Close any all-vertex path by adding one universal vertex.

Starting hint: A universal vertex is adjacent to every original vertex.

Answer & reasoning
Step by step
  1. For an undirected graph with at least two vertices, add z and edges from z to all original vertices.
  2. An original Hamiltonian path u→…→v becomes the cycle z→u→…→v→z.
  3. Conversely, delete z from any Hamiltonian cycle of the new graph to get a path through every old vertex. Tiny inputs can be handled separately; a cycle certificate is polynomial to check.

given G, add a new vertex z joined to every vertex of G, giving G′. If G has a Hamiltonian path from u to v, then z–u–…–v–z is a Hamiltonian cycle of G′. Conversely a Hamiltonian cycle of G′ passes through z once; deleting z leaves a path through every vertex of G. Membership in NP is clear (the cycle is the certificate).

Question 51 · hard

Two-colouring is easy (BFS, Lecture 11) but three-colouring is NP-complete. Explain why the BFS approach breaks down for three colours.

In simpler words: See why two colours force choices but three colours do not.

Starting hint: After colouring one vertex, count its neighbour’s available colours.

Answer & reasoning
Step by step
  1. With two colours, each neighbour has just one allowed colour.
  2. With three, each neighbour may have two allowed colours, and choices can interact across distant edges.
  3. Thus the forced BFS procedure no longer solves every case. This explains why that argument fails, not why every possible algorithm must be exponential.

With two colours, choosing a component’s first colour forces every neighbour to use the other colour; BFS can detect a conflict. With three colours, a neighbour can have two choices, and those choices affect later edges. The simple forced-colouring argument therefore fails. Backtracking may explore exponentially many choices, but that is not a proof that every possible algorithm must take exponential time.

Question 52 · hard

Give a simple algorithm that always finds a vertex cover at most twice the size of the smallest one, and prove the factor of 2.

In simpler words: Cover both ends of disjoint edges and compare with any optimum.

Starting hint: Each chosen edge forces every cover to include at least one endpoint.

Answer & reasoning
Step by step
  1. Pick an uncovered edge, add both endpoints, and discard every edge now covered. Continue until none remain.
  2. Chosen edges have no shared endpoints, so they form a matching of size r. Every cover needs at least r vertices.
  3. Your cover uses exactly 2r vertices, hence at most twice optimum. “Maximal” means no more disjoint edges can be added; it need not be the largest matching.

while some edge is uncovered, pick one and put both its endpoints into the cover. The chosen edges share no endpoints (each new edge was uncovered by all earlier endpoints), so they form a matching M. Any vertex cover, including the optimal one, must contain at least one endpoint of every edge of M, so OPT ≥ |M|. Our cover has exactly 2|M| vertices, hence at most 2 × OPT.

Question 53 · hard

For points in the plane (where the triangle inequality holds), prove that walking around the minimum spanning tree gives a travelling-salesman tour at most twice the optimal length.

In simpler words: Compare an MST walk with the unknown best tour.

Starting hint: An optimal tour with one edge removed is a spanning tree.

Answer & reasoning
Step by step
  1. Therefore the MST weight is at most the optimal tour length.
  2. Traverse each tree edge in both directions: a closed walk of length 2·MST visits every vertex.
  3. Skip repeated vertices. Triangle inequality ensures a direct shortcut is no longer than the replaced detour. The resulting tour costs at most 2·OPT.

remove one edge from the optimal tour: what remains is a spanning tree, so MST ≤ OPT. Doubling every MST edge gives a closed walk that visits all vertices with length 2 × MST ≤ 2 × OPT. Walk it, skipping vertices already visited; by the triangle inequality each shortcut is no longer than the detour it replaces, so the resulting tour is at most 2 × MST ≤ 2 × OPT.

Question 54 · hard

SAT is in NP because a satisfying assignment is a short certificate. Is “this formula is unsatisfiable” obviously in NP? Explain.

In simpler words: Distinguish showing that one assignment works from showing none work.

Starting hint: A failed candidate does not rule out the other candidates.

Answer & reasoning
Step by step
  1. A satisfying assignment is a short witness: check every clause.
  2. For unsatisfiability, no universal polynomial-size certificate with a polynomial-time checker is known; restricted cases may still have easy proofs.
  3. UNSAT belongs to co-NP. Whether it also belongs to NP is unresolved and equivalent to NP=co-NP. Do not turn “unknown” into “impossible.”

No general polynomial-size, polynomially checkable certificate for unsatisfiability is known. Such certificates do exist for some restricted formulas. UNSAT is in co-NP because its no-instances have satisfying assignments as certificates. Whether UNSAT is also in NP is equivalent to NP = co-NP and remains open; exhaustive enumeration is one method, not a proven necessity.

Question 55 · hard

Apply the 3-SAT to vertex cover reduction to the formula with clauses {x, y, ¬z} and {¬x, y, z}. How many vertices does the graph have, what cover size is asked for, and which vertices form a cover for the assignment x = y = z = true?

In simpler words: Count the small building blocks, then cover their edges.

Starting hint: Use one vertex from each variable pair and two from each clause triangle.

Answer & reasoning
Step by step
  1. There are 3 variable edges: 6 vertices. Two clause triangles add 6 more, giving 12; the target is 3+2·2=7.
  2. Select variable vertices x,y,z. In triangle (x,y,¬z), leave x out and select y,¬z. In triangle (¬x,y,z), leave y out and select ¬x,z.
  3. Each variable edge is covered; two vertices cover every triangle edge. A skipped clause vertex has its same-literal variable endpoint selected, so its cross edge is covered too.

n = 3 variables and c = 2 clauses give 2·3 + 3·2 = 12 vertices and a target cover size of n + 2c = 7. Variable gadgets: take the true literals x, y, z (3 vertices). Clause triangle {x, y, ¬z}: its x-vertex’s cross edge is already covered from the variable side (x is true), so take the other two, the y-vertex and the ¬z-vertex. Triangle {¬x, y, z}: y is true, so take the ¬x-vertex and the z-vertex. Total 3 + 2 + 2 = 7 vertices, covering every variable edge, every triangle edge and every cross edge.