COMP526 question bank

15 mock exam parts and 26 exercises from Tutorials 1–7. Open the steps for a hint, then reveal the worked answer. The solutions are study notes checked against the questions.

Complexity and logic

Mock 1A

Give the worst-case order of growth of Mergesort.

Show steps

Write the recurrence T(n) = 2T(n/2) + Θ(n). The linear merge work repeats across log₂ n levels.

Show answer

Θ(n log n).

Mock 2A

Compare f(n) = 84√n + 31n log log n + 4n and g(n) = 24n^(3/2) + 66n + 43·2^(−n)log n as n grows.

Show steps

Identify the dominant terms and take their ratio. log log n grows more slowly than √n.

Show answer

f = o(g).

Mock 4A

Negate ∃x ∀y [P(x) ⇒ Q(y)].

Show steps

Flip each quantifier and use ¬(P ⇒ Q) = P ∧ ¬Q.

Show answer

∀x ∃y [P(x) ∧ ¬Q(y)].

Tutorial 1 · 1

Group the equivalent formulas in the handout. In question order: (1) A⇒B, (2) (A⇒C)∧(B⇒C), (3) B⇒A, (4) (A∧C)∨(B∧C), (5) ((A∧C)⇒B)∧((A∧¬C)⇒B), (6) (A∨C)∧(B∨C), (7) ¬A∨B, (8) (A∧B)∨C, (9) (A∨B)∧C, (10) (A∨B)⇒C, (11) ¬(B∧¬A).

Show steps

Replace implications by disjunctions. Apply De Morgan's laws and distribute common factors. For (5), use the fact that exactly one of C and ¬C is true.

Show answer

The groups are {1,5,7}, {2,10}, {3,11}, {4,9}, {6,8}.

Tutorial 1 · 2

Using P(p,q) to mean p obeys q, write and negate the statement that S contains a dictator. Explain the negation in plain English.

Show steps

Choose the potential dictator first. Then quantify over every person who would have to obey them. Negation flips both quantifiers.

Show answer

∃p∈S ∀q∈S P(q,p). Its negation is ∀p∈S ∃q∈S ¬P(q,p). Every potential dictator has at least one person who does not obey them.

Tutorial 1 · 3

Formalise and negate the handout's definition of f = O(g) for positive integer inputs.

Show steps

Put the constant and threshold before the input quantifier. Negate the implication by keeping its premise and negating its conclusion.

Show answer

∃C>0 ∃N ∀n (n>N ⇒ f(n)≤Cg(n)). Its negation is ∀C>0 ∀N ∃n (n>N ∧ f(n)>Cg(n)). Every proposed bound fails at some input beyond its threshold.

Tutorial 2 · 1

Prove by induction that Σ from k=0 to h−1 of 2ᵏ equals 2ʰ−1.

Show steps

Check h=0 with an empty sum, then append the next term 2ʰ.

Show answer

The next sum is (2ʰ−1)+2ʰ=2ʰ⁺¹−1, so the identity holds for all h≥0.

Tutorial 2 · 2

For T(0)=3 and T(n)=T(n−1)+4, compute T(0) through T(5), guess a closed form and prove it by induction.

Show steps

Write the first six values. In the induction step, substitute the assumed formula into T(n+1)=T(n)+4.

Show answer

3,7,11,15,19,23. T(n)=4n+3. The base is T(0)=3, and the step gives 4n+3+4=4(n+1)+3.

Tutorial 2 · 3

Find the dominant terms and compare all pairs using o, O, Θ, Ω and ω. f₁=17n+8n log n+3n^(3/2), f₂=5·3^(n/2)+2n^(1/3)+1/7, f₃=(log n)^4+3(log n)^2+17.

Show steps

Rank polylogarithmic, polynomial and exponential terms. For strict growth comparisons take the ratio of the lower growth function to the higher one.

Show answer

f₃=Θ((log n)^4), f₁=Θ(n^(3/2)), f₂=Θ(3^(n/2)). In the order f₃,f₁,f₂, every earlier function is o and O of each later one. Each later function is ω and Ω of each earlier one. No distinct pair is Θ-equivalent.

Tutorial 2 · 4

Prove that repeatedly subtracting k from n until the result is below k computes n mod k. Give its running time.

Show steps

Maintain t=n−jk after j subtractions and t≥0. Each iteration preserves the residue class and reduces t by k.

Show answer

At termination 0≤t<k, so t is the unique remainder. There are exactly ⌊n/k⌋ subtractions and the unit-cost runtime is Θ(1+⌊n/k⌋).

Compression and error correction

Mock 1B

Decode the RLE bit string 1000110101100100010000010011.

Show steps

Using the convention of a starting bit followed by Elias gamma run lengths, take the first bit as 1. For each run, count the leading zeroes and read that many additional bits after the first 1. Split the remainder as 0001101 / 011 / 00100 / 010 / 000010011.

Show answer

The run lengths are 13, 3, 4, 2, 19. Expand to 13 ones, 3 zeroes, 4 ones, 2 zeroes and 19 ones. The paper does not restate the encoding convention.

Mock 1C

Decode MTF indices [0,2,4,0,3,4,2,5,4,2,0,4,4] starting with Q = [B,E,I,R,T,W]. Show each queue state.

Show steps

Read the symbol at each zero-based position, emit it and move it to the front. Queue states: BEIRTW → IBERTW → TIBERW → TIBERW → ETIBRW → RETIBW → TREIBW → WTREIB → IWTREB → TIWREB → TIWREB → ETIWRB → RETIWB.

Show answer

BITTERTWITTER.

Mock 2B

Decode (7,4) Hamming block B₇…B₁ = 1111001 and identify any corrected bit.

Show steps

Use even parity on positions 1, 2 and 4 and form syndrome s₄s₂s₁. The checks give 001, so flip B₁, then read data positions 7, 6, 5, 3.

Show answer

A one-bit error occurred at position 1. Corrected block: 1111000. Message D₃…D₀ = 1110.

Mock 4B

Build a Huffman tree for A=.10, B=.20, C=.40, D=.25, E=.05. Put the lower weight on the left and break equal-weight ties with the smallest contained letter. Give codes, bit rate and time complexity.

Show steps

Merge E+A=.15, then (EA)+B=.35, then D+(EAB)=.60, then C+(DEAB)=1. Follow 0 on left and 1 on right. Weight each code length by its probability.

Show answer

C=0, D=10, E=1100, A=1101, B=111. Average length 2.10 bits per symbol. A heap-based build takes Θ(k log k) in the worst case for k symbols.

Tutorial 6 · 1

Huffman-encode HANNAHBANSBANANASMAN. Give frequencies, merge order, codes, encoded bits and compression ratio. Lower weights go left, with alphabetical tie-breaking.

Show steps

Count characters. Merge the two smallest nodes and reinsert their sum until one tree remains. Read left edges as 0 and right edges as 1. Compare bit counts against the chosen baseline.

Show answer

A7 N6 B2 H2 S2 M1. M+B→3, H+S→4, BM+HS→7, N+A→13, BHMS+AN→20. Codes M=000 B=001 H=010 S=011 N=10 A=11. Encoded: 01011101011010001111001100111101110110110001110 (47 bits). The official solution uses log₂(6) bits per symbol as its baseline, giving 47/(20 × log₂(6)) ≈ 90.9%. Against an actual 3-bit fixed-width code, the ratio is 47/60 ≈ 78.3%. Against 8-bit bytes it is 47/160 ≈ 29.4%.

Tutorial 6 · 2

Build a Huffman code with F:1, L:1, O:4, S:2, T:2, then decode 1100001011110001101111.

Show steps

Merge F+L, then FL+S, then T+FLS, then O+FLST. Traverse from the root for every symbol and restart at each leaf.

Show answer

O=0 T=10 F=1100 L=1101 S=111. Decoded text: FOOTSTOOLS.

Tutorial 7 · 1

Run-length encode 000000000011111110001111100000000 and compute the compression ratio.

Show steps

Find the maximal alternating runs. Write the starting bit followed by the Elias gamma code of each positive run length.

Show answer

Lengths 10,7,3,5,8. Code: 0000101000111011001010001000. Compressed/original is 28/33 ≈ 84.8%.

Tutorial 7 · 2

Decode the RLE string 00010100101001110110001001011.

Show steps

Read the starting bit. Split the remainder into Elias gamma codewords by counting the zeroes before each leading 1. Alternate output bits between runs.

Show answer

Lengths 5,5,7,3,9,3. Output: 00000111110000000111000000000111.

Tutorial 7 · 3

Assume an algorithm H decides whether any program halts. How would you compute the Kolmogorov complexity of a string S with H? What follows about H?

Show steps

Enumerate programs by length. Use H to discard nonhalting programs, then execute each remaining program to completion and compare its output with S.

Show answer

The first program producing S has minimum length, so this would compute K(S). For a fixed universal programming system K is uncomputable, hence H cannot exist as a general algorithm.

Data structures and string matching

Mock 2C

Insert 55,53,76,26,14,43,51,41,50,10,23,20,83,29,1 into an empty ordinary BST. Which keys are compared during a search for 83?

Show steps

Start at the root. Go right when the target is greater than the current key and left when it is smaller.

Show answer

55 → 76 → 83.

Mock 3A

Find all k matches of a length-m pattern in a length-n text with an existing suffix array. Give the running time.

Show steps

Use two binary searches to find the contiguous interval whose suffixes begin with the pattern. Each comparison inspects at most m characters. Report the indices in that interval.

Show answer

Worst-case Θ(m log n + k) for the straightforward character-by-character method.

Mock 4C

Build the DFA transition table for pattern dbbabdbbabbc, states 0–11 and alphabet a,b,c,d.

Show steps

For state q and character c, append c to the length-q pattern prefix. Find the longest suffix that is also a pattern prefix. State 12 signals a match.

Show answer

Columns 0–11: a=[0,0,0,4,0,0,0,0,9,0,0,0]; b=[0,2,3,0,5,0,7,8,0,10,11,0]; c=[0,0,0,0,0,0,0,0,0,0,0,12]; d=[1,1,1,1,1,6,1,1,1,1,6,1].

Mock 5A

Name the three main stack operations and their costs with a linked list.

Show steps

Use the head of the linked list as the top.

Show answer

Push inserts at the head, pop removes and returns the head, and peek returns its value. Each is Θ(1).

Mock 5B

Build a suffix trie, suffix tree and suffix array of abaabaaab$. Compare their space costs.

Show steps

Insert every suffix character by character to obtain the trie. Compress each maximal single-child chain into one edge to obtain the tree. Visit leaves in lexicographic order, with $ first, to obtain the array.

Show answer

Compressed tree as parent → edge:(leaf or children), using zero-based leaf labels: root → $:9, a:{a:{ab$:5,b:{$:6,aaab$:2}},b:{$:7,a:{aab$:3,abaaab$:0}}}, b:{$:8,a:{aab$:4,abaaab$:1}}. Expand each edge into one edge per character to obtain the full trie. Suffix array = [9,5,6,2,7,3,0,8,4,1]. The suffix trie can take Θ(n²) space. A suffix tree using source-text intervals and a suffix array both take Θ(n) space, with the array generally using less memory.

Tutorial 3 · 1

Implement a FIFO queue using two stacks A and B.

Show steps

Keep newly enqueued items in A. When B is empty, reverse A into B by repeated pops and pushes.

Show answer

ENQUEUE(x) pushes onto A. DEQUEUE transfers A to B if necessary and then pops B, or reports empty if both stacks were empty. Each item transfers once, giving amortised O(1) per operation.

Tutorial 3 · 2

Implement a fixed-capacity array deque with constant-time operations and a full-state test.

Show steps

Use a circular array of capacity C, a head index h and a count s. Use modulo C for wraparound. Check empty before popping and full before appending.

Show answer

APPEND writes at (h+s) mod C. APPENDLEFT decrements h modulo C and writes there. POP reads (h+s−1) mod C. POPLEFT reads h and advances it modulo C. Adjust s by ±1. Empty iff s=0, full iff s=C. All operations are O(1).

Tutorial 3 · 3

Prove that insertion with bubble-up preserves a min-heap.

Show steps

Adding the new key at the next leaf preserves completeness. The only possible order violation lies between the inserted key and its parent. Swapping with a larger parent fixes that edge and leaves only a possible violation one level closer to the root.

Show answer

Each swap moves the new key upward, and the demoted parent is at most the original descendants below it. On reaching the root or a parent no larger than the key, every edge has min-heap order.

Tutorial 3 · 4

Insert 88,16,14,52,57,80,9,55 into an array-backed min-heap. Show every state and the state after REMOVEMIN.

Show steps

Append and bubble up for each insertion. For removal move the last element to the root and sift it down using the smaller child.

Show answer

[88] → [16,88] → [14,88,16] → [14,52,16,88] → [14,52,16,88,57] → [14,52,16,88,57,80] → [9,52,14,88,57,80,16] → [9,52,14,55,57,80,16,88]. After removal: [14,52,16,55,57,80,88].

Tutorial 3 · 5

Insert 7,4,15,11,6,17,3,9,8,12 into a BST. Draw it, label heights and unbalanced vertices, then rebalance it with one rotation.

Show steps

Use leaf height 0. Compute heights bottom-up. Left and right children are listed in order, with a dash marking an empty child.

Show answer

Before: 7:(4,15), 4:(3,6), 15:(11,17), 11:(9,12), 9:(8,–). Heights: 7=4, 15=3, 11=2, 4=9=1, all others 0. Vertices 7 and 15 are unbalanced. Rotate right at 15, making 11 the right child of 7 and 12 the left child of 15. After: 7=3, 11=2, 4=9=15=1, all others 0.

Sorting networks and algorithm design

Mock 3B

On five wires, apply compare-exchanges (0,1), (2,4), (1,3), (0,2), (3,4), (1,2). Find the count, depth and output for [4,3,1,2,5]. Does it sort every input?

Show steps

Send smaller values to the lower-numbered wire. Pack independent comparisons into layers: [(0,1),(2,4)], [(1,3),(0,2)], [(3,4),(1,2)]. Try binary inputs to find a counterexample.

Show answer

6 comparators, depth 3, output [1,2,3,4,5]. It fails on [0,0,1,0,1], which passes through unchanged.

Mock 3C

Given n lowercase words of length m, find two anagrams or report that no pair exists. Give pseudocode and complexity.

Show steps

For each word, count its 26 letters. If the resulting tuple is already in a dictionary, return its stored word and the current word. Otherwise store the tuple and word. Return no pair after the loop.

Show answer

Equal count vectors identify anagrams. Worst-case expected Θ(nm) time with standard hashing and a fixed alphabet, using O(n) auxiliary space. A deterministic alternative sorts the count vectors and scans adjacent pairs in O(nm + n log n).

Mock 5C

Return the original indices of a closest pair of floating-point numbers in an array.

Show steps

Sort pairs (value, original index) by value. Scan consecutive sorted pairs and retain the pair with the smallest difference. Any nonadjacent pair has an adjacent gap no larger than its own gap.

Show answer

Return the retained indices. Θ(n log n) worst-case time with Mergesort and O(n) auxiliary space. Inputs with fewer than two elements contain no pair.

Tutorial 1 · 4

Prove the given Selectionsort is correct using an invariant, induction and termination.

Show steps

After iteration i, the prefix contains the i smallest elements of the original array in sorted order. Begin at i=0 with an empty prefix. The next swap takes the smallest remaining value and preserves the multiset.

Show answer

The invariant holds by induction and at i=n covers the whole array, which is therefore sorted.

Tutorial 4 · 1

Find the peak of a strictly bitonic array in O(log n). Explain the Ω(n) worst-case lower bound for finding the first turning point in a tritonic array.

Show steps

For the bitonic case, compare a[mid] to a[mid+1]. For the lower bound, start with a strictly increasing array and hide a descent by swapping one adjacent interior pair.

Show answer

The local slope directs binary search towards the peak. For tritonic arrays, choose Ω(n) disjoint candidate pairs. Any probe can rule out at most one untouched pair along the increasing-array transcript. Until all but one candidate is excluded, different valid tritonic arrays yield identical observations but have different peaks.

Tutorial 4 · 2

Bound Insertion Sort when each element is at most k positions from its sorted location.

Show steps

Track each element by its sorted rank, breaking ties stably. An inversion between original positions i<j requires j−i<2k because both ranks move at most k. Each adjacent swap removes exactly one inversion.

Show answer

There are O(nk) inversions. Including loop overhead gives O(n+nk), hence O(nk) for k≥1. At k=0 the array is already sorted and scanning takes Θ(n).

Tutorial 4 · 3

Show why applying an identical fixed swap sequence to two distinct permutations cannot sort both.

Show steps

Each swap is invertible. Reverse the sequence to recover the input uniquely from its output.

Show answer

Distinct inputs must yield distinct outputs, so they cannot both become the same sorted permutation.

Tutorial 4 · 4

Explain the Ω(n log n) radix-sort running time for n distinct numerical keys under a fixed radix.

Show steps

For a fixed base b, d digits provide only bᵈ distinct codes. Each complete digit pass processes all n entries.

Show answer

d≥⌈log_b n⌉ and each pass takes Ω(n). With constant b, n digit-pass work is Ω(n log n). This bound assumes the fixed-radix, full-pass model. A radix that grows with n can change the bound.

Graph traversal and shortest paths

Tutorial 5 · 1

Given adjacency lists 1:8,7,3 / 2:3,7,5 / 3:7,1,2 / 4:6,5 / 5:2,6,4 / 6:5,4 / 7:8,1,2,3 / 8:7,1, list edges, draw without crossings if possible, trace DFS and BFS from 1 and find dist(1,4).

Show steps

Treat each pair as undirected. Use the given neighbour order, recursively for DFS and with enqueue-time marking for BFS. For a planar layout, draw triangles 1–8–7, 1–7–3, 2–3–7 and attach the triangle 4–5–6 to 2 via 2–5.

Show answer

Edges: 1–8,1–7,1–3,2–3,2–7,2–5,3–7,4–6,4–5,5–6. DFS: 1,8,7,2,3,5,6,4. BFS: 1,8,7,3,2,5,6,4. Distance 4, for example 1–7–2–5–4.

Tutorial 5 · 2

Extend BFS to compute every distance from u and give a shortest path from each reachable vertex back to u.

Show steps

Set dist[u]=0, other distances to infinity and parent entries to null. When first discovering w from v, set dist[w]=dist[v]+1 and parent[w]=v before enqueueing.

Show answer

Follow parent pointers from a reachable vertex to u. Unreachable vertices retain infinity and have no path. BFS takes Θ(V+E) time with adjacency lists and O(V) extra space.

Tutorial 5 · 3

Apply Dijkstra from vertex 1 to the weighted graph in the handout. Give the distance to every vertex.

Show steps

Use the PDF adjacency lists. Treat the inconsistent 0.8 entry in row 3 as the undirected 3–7 edge shown in row 7. Start with 0 at vertex 1 and infinity elsewhere, then repeatedly settle the smallest tentative distance and relax outgoing edges.

Show answer

Settlement order: 1,6,2,7,5,3,4. Distances in vertex order 1–7: [0,1.8,3.7,4.8,3.2,1.3,2.9]. The best route to 4 is 1–2–7–3–4.

Matching algorithms

Tutorial 1 · 5

Run student-proposing Gale–Shapley using the preference tables in the handout. Find two other stable matchings.

Show steps

Let each rejected student apply to their next company. Companies keep their most preferred applicant so far. For other matchings, check every mutually preferred unmatched pair for a blocking pair.

Show answer

In student order s1,s2,s3,s4, the algorithm returns (c3,c1,c4,c2). The other stable matchings are (c1,c3,c2,c4) and (c3,c1,c2,c4).