Past exam of the computer science course of the University of Oxford 2018 Algorithms 2 c Solution 2026-10-31
Root the tree arbitrarily. For each vertex , let be the minimum vertex cover size in its descendant subtree, conditional on selecting , and the corresponding minimum conditional on omitting . Process the vertices in postorder traversal. For every child of ,At a leaf of a rooted tree, the empty sums give . Return at the root .
For algorithm correctness, if is selected, each child subtree may independently use its cheaper state, since the connecting edge is already covered by . If is omitted, each child must be selected to cover its connecting edge. Distinct child subtrees have no edges between them because the input is a tree. These observations prove the recurrences by structural induction. Each edge contributes constant work once, giving time complexity and space with adjacency lists. The single-vertex tree correctly has optimum zero. This is minimum vertex cover of a tree by dynamic programming.
Past exam of the computer science course of the University of Oxford 2018 Algorithms 2 f Solution 2026-10-31
For a connected graph with at least one edge, run depth-first search and output the set of internal vertices of a rooted tree in its discovery tree . Part (d) proves that is a vertex cover. It is also connected: every ancestor of an internal vertex is internal, so the graph path in from that vertex to the root stays inside . The root is internal when .
For the approximation guarantee, choose a maximum-size proper matching in a rooted tree of , whose existence is supplied. It is used only in the analysis; the algorithm need not construct it. Since every matched edge uses two distinct vertices,By part (e), . ThereforeThe final inequality holds because every vertex cover of , connected or otherwise, must use at least one distinct endpoint for each of the disjoint edges in . Thus this is a 2-approximation algorithm in time complexity.
For completeness, a disconnected input needs a feasibility check: if two different connected components of a graph contain edges, no connected vertex cover can meet both. If exactly one component contains edges, run the construction on that component and ignore isolated vertices. If there are no edges, the empty vertex cover is optimal when an empty solution is permitted; if a nonempty connected solution is required, any single vertex is optimal for a nonempty input. These conventions cover the boundary cases omitted from the main approximation argument.
Depth-first search computes minimax search values with much less live storage and naturally supports alpha-beta pruning. A parent's value needs only its current best child value and the next child to visit. Once a child subtree has been evaluated, its internal search nodes can be discarded; a final value cannot usually be computed from a nonterminal frontier alone.
With branching factor and horizon , breadth-first search stores a frontier of order . A depth-first search implementation storing sibling lists uses space complexity; lazy successor generation can reduce this to frames plus game-state storage. Both unpruned traversals have time complexity for . Depth-first search also supplies a completed sibling outcome early, allowing alpha-beta pruning to reject later subtrees before generating them.
The first assertion is true. Each deletion removes a value with no support in an adjacent constraint domain. If a complete solution still used that value, the solution’s neighboring value would supply exactly such a support, a contradiction. By mathematical induction, AC-3 never deletes a value used by an original solution. An empty constraint domain therefore proves that no solution exists.
The second assertion is false. Take three Boolean variables with constraint domains and the binary constraints , , . Every value has the opposite value as support across each edge, so AC-3 deletes nothing and returns true. Yet and imply , contradicting . Arc consistency checks local support, not compatibility of all supports in one complete assignment.
Every value has pairwise support, but following the three inequality constraints makes a complete assignment impossible
. Details. The third assertion is true under the usual explicit-input, constant-cost constraint-checking model. With variables, constrained pairs and maximum constraint domain size , AC-3 has time complexity in Big O notation. A revision costs ; each deletion can re-enqueue incoming arcs, and each constraint domain loses at most values, giving revisions including the initial arcs. For two-valued constraint domains, , so this is , linear in the explicit input size. This uses fixed-size relations, or already combined constant-time tests per pair. “Binary” normally describes constraint arity, not two-valued constraint domains; the latter restriction is the extra hypothesis needed here. As usual, initially empty constraint domains should be rejected before entering the algorithm, including isolated variables.
Interpret MyAC as doing at least one initial sweep, then repeating while the preceding sweep deleted a value. Its loop guard otherwise has no initialized truth condition. Both procedures apply the same support-based deletion rule, so both preserve every solution and terminate because finite constraint domains only shrink. Both return false on a detected empty constraint domain; neither successful return establishes satisfiability.
If a sweep changes no constraint domain, every directed arc has been revised against unchanged constraint domains, so all arcs satisfy arc consistency. Conversely, AC-3 places every potentially affected incoming arc back on its work list after a deletion. Its empty work list therefore also establishes arc consistency. When both run to successful completion, they compute the same arc-consistency closure, independently of revision order. To see maximality, any subdomains of the initial constraint domains that satisfy arc consistency survive every revision: each of their values retains a support inside those subdomains. Thus neither procedure can delete a value belonging to any such fixed point. Early failure may leave different intermediate constraint domains, but both failures correctly prove impossibility.
Their scheduling costs differ. AC-3 directs work toward arcs that may have lost supports, with standard time complexity . The full-sweep arc consistency method revisits all arcs after even one remote change. There are at most value deletions, so at most sweeps; a direct implementation including a scan for empty constraint domains costsIf empty-domain detection is maintained during revisions rather than rescanned, the familiar comparison is versus , apart from initialization. These are upper bounds, not exact costs on every input.
In practice MyAC is simple and may have low overhead or benefit from a fortunate sweep order. It can also waste many scans after changes propagate slowly opposite to that order. AC-3 incurs work-list bookkeeping but normally avoids those unrelated revisions. Both inherit the inability of arc consistency to decide arbitrary constraint satisfaction problems.
For a finite constraint satisfaction problem with variables, all complete assignments have depth when each step assigns one new variable. Thus the shallowest-solution property of breadth-first search offers no advantage: every complete solution is already at that depth.
Depth-first search with backtracking stores a path and pending choices, using auxiliary space with ordinary explicit choice bookkeeping, or when each level stores only a current value index. Breadth-first search may store an exponentially large frontier, up to partial assignments. Depth-first search can also combine naturally with immediate constraint propagation and undoing changes. The finite depth avoids the infinite-branch obstruction of unrestricted depth-first tree search. Neither traversal removes the possible exponential time complexity.
The residual constraint graph is a tree, rooted conveniently at , with children and with a child of . Solve it by the tree-structured constraint satisfaction algorithm: enforce arc consistency from children toward their parents, then choose a surviving root value and select supported child values in the opposite direction.
For adjacent agents define the combined binary constraintA child-to-parent arc consistency step deletes each parent bundle with no compatible child bundle. Process the edges in the order , , , .
First, needs a nonempty subset of . Supporting reduces 's constraint domain toIndeed, leaves only for but gives value ; and leave no possible item for . Each of the four retained choices has a compatible choice for .
Next, supporting reduces 's constraint domain to all nonempty subsets of . To see why item cannot remain in 's bundle, a disjoint compatible bundle from would have to be , but then values its own bundle at and 's at least at . Conversely any nonempty subset of is compatible with .
Supporting next reduces 's constraint domain toIf held item , disjointness would force , whose value is below 's value for 's bundle. If holds but not , then , and needs value at least to avoid envying . If holds neither, supports every nonempty subset of .
Finally, supporting leavesThe removed choices contained both and , leaving no item for . Every displayed choice has a compatible choice for .
Choose , then supported child values, givingItems remain unallocated, which this variant expressly permits. To check every envy-free allocation inequality, the matrix of agents' additive valuations of these bundles, with rows and columns both ordered , isEach diagonal entry is at least every entry in its row. The bundles are nonempty, pairwise disjoint, and contain only positively valued items, so all remaining requirements hold.
Why does selecting supported children suffice? The residual constraint graph has no graph cycle, so different child subtrees have no constraints between them. Child-to-parent arc consistency has already ensured a compatible continuation below every retained parent value. Applying this observation recursively proves that the downward choices complete a solution without backtracking. With variables and maximum constraint domain size , the basic compatibility checks require time complexity in Big O notation, counting each binary constraint evaluation as one operation; evaluating bundle sums has its own input-dependent cost.
Past exam of the mathematics course of the University of Cambridge 2006 ia Paper 5 1 a Solution Created 2026-09-24 Updated 2026-10-14
Use the usual unit-cost model for Standard ML list constructors and fixed-size arithmetic. The input size in the list examples is the number of list elements, rather than the size of the integer entries. Inspecting only the first constructor has constant time complexity:No tail is traversed. The running time is .
sml
fun firstOrZero [] = 0
| firstOrZero (x :: _) = x; Past exam of the mathematics course of the University of Cambridge 2006 ia Paper 5 1 b Solution Created 2026-09-24 Updated 2026-10-14
A Standard ML length function visits each list constructor once:Writing for its time complexity, and . Thus . Arithmetic is treated as unit cost; the example concerns list traversal rather than arbitrary-precision arithmetic.
sml
fun length [] = 0
| length (_ :: xs) = 1 + length xs; Past exam of the mathematics course of the University of Cambridge 2006 ia Paper 5 1 c Solution Created 2026-09-24 Updated 2026-10-14
Use merge sort on a list of integers:Here
sml
fun sort xs = mergeSort (op <=) xs;mergeSort denotes the standard merge sort implementation: split into two almost equal lists, recursively sort them, and combine them using the merge algorithm. Splitting and merging take linear time, and each recursion level has total input length . There are levels, so the worst-case time complexity is . Equivalently, . Past exam of the mathematics course of the University of Cambridge 2006 ia Paper 5 1 d Solution Created 2026-09-24 Updated 2026-10-14
Traverse the whole original list once for each of its elements:The outer structural recursion runs times, and each
sml
fun scan [] = ()
| scan (_ :: xs) = scan xs;
fun scanForEach [] whole = ()
| scanForEach (_ :: rest) whole =
(scan whole; scanForEach rest whole);
fun quadratic xs = scanForEach xs xs;scan whole visits constructors. In the ordinary source-evaluation cost model, the time complexity is . This example counts executed traversals, without assuming an optimizing compiler that removes deliberately unused computations. Past exam of the mathematics course of the University of Cambridge 2006 ia Paper 5 1 e Solution Created 2026-09-24 Updated 2026-10-14
For a nonnegative integer parameter , make both branches of a structural recursion execute:The semicolon sequences two calls, so this is not a conditional choosing just one branch. The recursion tree has leaves and calls. Its time complexity satisfies , giving . Here is the parameter specified by the question, not its binary encoding length; only calls are simultaneously on the stack.
sml
fun binaryWalk 0 = ()
| binaryWalk n = (binaryWalk (n - 1); binaryWalk (n - 1)); Past exam of the mathematics course of the University of Cambridge 2006 ia Paper 5 3 Solution Created 2026-09-24 Updated 2026-10-14
Extract one four-bit digit at a time, beginning at the most significant end of the Java The logical right bit shift
int. A lookup string supplies characters, but no library performs the conversion:java
static String toHex(int value) {
String digits = "0123456789abcdef";
String answer = "";
boolean started = false;
for (int shift = 28; shift >= 0; shift -= 4) {
int digit = (value >>> shift) & 15;
if (started || digit != 0 || shift == 0) {
answer = answer + digits.charAt(digit);
started = true;
}
}
return answer;
}>>> inserts zeros, and the bit mask 15 retains exactly the low four bits of the shifted word. Each emitted character is therefore the corresponding hexadecimal digit. The started flag suppresses leading zero digits; the shift == 0 exception makes zero produce "0", rather than an empty string.A negative Java integer uses two's complement. Its top bit is set, so the first extracted digit is between eight and fifteen and all eight digits are emitted. We interpret its original 32-bit pattern, without taking an absolute value or negating a potentially unnegatable minimum integer. In particular,
toHex(19) returns "13", toHex(-1) returns "ffffffff", and toHex(Integer.MIN_VALUE) returns "80000000". There are exactly eight iterations, so for this fixed word size the time complexity is constant. Past exam of the mathematics course of the University of Cambridge 2006 ia Paper 5 6 b Solution Created 2026-09-24 Updated 2026-10-14
Represent a binary search tree by:Assume the provided For equality-type values, call
sml
datatype ('k, 'v) dict = Empty
| Branch of ('k, 'v) dict * 'k * 'v * ('k, 'v) dict;lookup d key returns NONE or SOME value, and update d (key, value) returns the updated binary search tree. Traverse the first dictionary, retaining only a key with the same value in the second:sml
fun intersection equal d1 d2 =
let
fun visit Empty result = result
| visit (Branch (left, key, value, right)) result =
let
val r1 = visit left result
val r2 =
case lookup d2 key of
NONE => r1
| SOME other =>
if equal (value, other)
then update r1 (key, value)
else r1
in
visit right r2
end
in
visit d1 Empty
end;intersection (op =) d1 d2. An explicit value comparison parameter also handles values for which Standard ML does not define built-in equality. This distinguishes absent keys from defined values without reserving a sentinel value.Every inserted entry belongs to both input dictionaries with the same value, so the result agrees with each. Conversely, each common equal-valued entry is visited in
d1, found in d2, and inserted. Any dictionary agreeing with both can contain only those entries. Thus the result is exactly the largest common dictionary, not merely an intersection of key sets. If d1 has entries, lookup height is , and maximum result-tree height during insertion is , the time complexity is for constant-cost comparisons. Logarithmic heights require a balancing assumption; an ordinary unbalanced binary search tree can have linear height. Past exam of the mathematics course of the University of Cambridge 2006 ia Paper 5 9 e Solution Created 2026-09-24 Updated 2026-10-14
A collections library can specify a
List<E> Java interface, with different implementations such as ArrayList<E> and LinkedList<E>. A method accepting List<E> can iterate or access elements according to the documented list contract without requiring one particular storage representation. Each implementation may also extend its own appropriate class superclass.The benefit is separating a usable contract from its implementation. A parameter restricted to a concrete
ArrayList<E> would exclude a linked list implementation and unnecessarily expose the storage choice. Requiring all providers to extend one concrete class would couple them to its implementation and consume Java's single class-inheritance relationship. Interfaces permit multiple implemented contracts, though clients must rely on the stated contract rather than assuming every optional operation is supported or has the same time complexity. Past exam of the mathematics course of the University of Cambridge 2007 ia Paper 5 1 c Solution Created 2026-09-24 Updated 2026-10-14
Assume head comparison and construction of one list cell take constant time. In the merge algorithm, every comparison removes one head from the recursive inputs, and evaluation stops as soon as either is empty. For lengths , at most comparisons and the same number of newly constructed cells are required; the untouched suffix is shared. Inputs which keep both lists nonempty until the last comparison attain this bound. ThusAn initially empty input makes this particular implementation constant-time; not every pair requires linear work.
The balanced merge sort spends time per call on list length, splitting and merging. Hence its time complexity satisfiesAt each recursion level the lengths of its disjoint subproblems sum to , so the work per level is , and balanced splitting gives levels. ConsequentlyThe length and splitting traversals change the constant factor, not this asymptotic order; repeatedly inserting elements into a sorted list would not give the same complexity.
Past exam of the mathematics course of the University of Cambridge 2007 ia Paper 5 9 b ii Solution Created 2026-09-24 Updated 2026-10-14
Use recursive dependency evaluation with memoization. After an edit, invalidate all cell states. To evaluate one formula, recursively obtain its dependencies before storing its own result. This is a depth-first search of the dependency graph; a visiting mark identifies a cycle, and a done mark avoids repeated evaluation of a shared dependency. The following single class implements the design, with public nested interfaces for formula extensions:The outer loop's order need not be a topological ordering, since recursion evaluates dependencies first. After an edit, callers can invoke
public final class Spreadsheet {
public enum Kind { EMPTY, LABEL, NUMBER, FORMULA }
public interface Lookup {
double valueAt(int row, int col);
}
public interface Formula {
double evaluate(Lookup values, int row, int col);
}
public static final class AddFormula implements Formula {
private final int dr1, dc1, dr2, dc2;
public AddFormula(int dr1, int dc1, int dr2, int dc2) {
this.dr1 = dr1; this.dc1 = dc1;
this.dr2 = dr2; this.dc2 = dc2;
}
public double evaluate(Lookup values, int r, int c) {
return values.valueAt(r + dr1, c + dc1)
+ values.valueAt(r + dr2, c + dc2);
}
}
private static final class Cell {
private final Kind kind;
private final String label;
private final double number;
private final Formula formula;
private Cell(Kind k, String s, double n, Formula f) {
kind = k; label = s; number = n; formula = f;
}
}
private static final Cell EMPTY =
new Cell(Kind.EMPTY, null, 0.0, null);
private final int rows, cols;
private final Cell[][] cells;
private final double[][] cache;
private final byte[][] state;
private final Lookup view = new Lookup() {
public double valueAt(int r, int c) {
return Spreadsheet.this.valueAt(r, c);
}
};
public Spreadsheet(int rows, int cols) {
if (rows < 0 || cols < 0) throw new IllegalArgumentException();
this.rows = rows; this.cols = cols;
cells = new Cell[rows][cols];
cache = new double[rows][cols];
state = new byte[rows][cols];
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) cells[r][c] = EMPTY;
}
private boolean inside(int r, int c) {
return r >= 0 && r < rows && c >= 0 && c < cols;
}
private void check(int r, int c) {
if (!inside(r, c)) throw new IndexOutOfBoundsException();
}
private void invalidate() {
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) state[r][c] = 0;
}
private void put(int r, int c, Cell cell) {
check(r, c); cells[r][c] = cell; invalidate();
}
public void setEmpty(int r, int c) { put(r, c, EMPTY); }
public void setLabel(int r, int c, String text) {
if (text == null) throw new IllegalArgumentException();
put(r, c, new Cell(Kind.LABEL, text, 0.0, null));
}
public void setNumber(int r, int c, double x) {
put(r, c, new Cell(Kind.NUMBER, null, x, null));
}
public void setFormula(int r, int c, Formula f) {
if (f == null) throw new IllegalArgumentException();
put(r, c, new Cell(Kind.FORMULA, null, 0.0, f));
}
public Kind kindAt(int r, int c) {
check(r, c); return cells[r][c].kind;
}
public String labelAt(int r, int c) {
check(r, c); return cells[r][c].label;
}
public double valueAt(int r, int c) {
if (!inside(r, c)) return 0.0;
if (state[r][c] == 2) return cache[r][c];
if (state[r][c] == 1)
throw new IllegalStateException("Cyclic formula dependency");
state[r][c] = 1;
try {
Cell cell = cells[r][c];
double answer;
switch (cell.kind) {
case NUMBER: answer = cell.number; break;
case FORMULA: answer = cell.formula.evaluate(view, r, c); break;
default: answer = 0.0;
}
cache[r][c] = answer;
state[r][c] = 2;
return answer;
} catch (RuntimeException error) {
state[r][c] = 0;
throw error;
}
}
public void recalculate() {
invalidate();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) valueAt(r, c);
}
}recalculate; ordinary valueAt calls also calculate lazily from the invalidated state. Empty and label cells contribute zero without destroying their display content. Relative references are interpreted at the formula's location, and off-grid references contribute zero as required.For an acyclic graph, mathematical induction over a topological ordering proves that each cached value equals the evaluation of current cell contents. Each cell becomes done at most once in a pass, so the time complexity is for cells and dependency references, plus formula arithmetic. The stack depth is at most the longest dependency path. A more elaborate implementation can record reverse dependencies and invalidate only cells affected by an edit.
The PDF gives no policy for circular formulas. Repeated numerical sweeps are not a general solution: a cell defined as itself plus one has no finite value, while a cell defined as itself plus zero has no unique value. The implementation therefore reports a cycle instead of looping or presenting an arbitrary stale value. An acyclic dependency graph is evaluated once per cell; circular dependencies are detected and rejected.
Past exam of the mathematics course of the University of Cambridge 2016 iii Paper 120 1 c Solution Created 2026-10-03 Updated 2026-10-06
Part (a)(i), applied to and , guarantees an accepted output of length at most . Its padded convolution of words has at most columns. Thus the dynamic programming search in part (b) reaches an accepting layer by this bound.
Each layer has at most twice the fixed number of states of , and each record has at most outgoing choices. These are constants for the fixed automatic structure for a group. Storing a pointer and a symbol takes constant time; copying whole partial output strings at every step would unnecessarily spoil this bound. Reconstruction also takes at most steps. Therefore automatic multiplication has linear time and bounded length increase:For nonempty inputs this is the requested time complexity. The additive merely includes the constant work on the empty word.
Past exam of the mathematics course of the University of Cambridge 2016 iii Paper 120 1 e Solution Created 2026-10-03 Updated 2026-10-06
Write the input word over an alphabet as . Starting with , obtain from by linear-time multiplication in an automatic structure with . Mathematical induction givesThe time complexity of step is at most a constant times . Summing the costs givesThe automatic structure for a group, and are fixed, so the required representative isFor the empty word, return in constant time.
Computational complexity theory studies the resources needed by an algorithm as a function of input size, after specifying the resource and computational model. For example, time complexity may count comparisons, and space complexity may count stored words. Worst-case time complexity is the greatest cost among inputs of size ; best-case and average costs are different measures.
An upper bound guarantees that a cost is no greater than the stated bound. A lower bound guarantees that it is no smaller. For a problem, an algorithm can establish an upper bound on what is achievable, while a problem lower bound must apply to every eligible algorithm in the chosen model. Bounds need not be tight. Concisely,
