Data Structures and Algorithms - Mock Exam 2
Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.
In questa pagina 7
Mock exam built on the model of the official sample written exams of the equivalent Italian course (Dati e Algoritmi, UniPD), not an official paper. Like the models it has two written parts of equal weight. Part 1 (Exercises 1-3: 3 + 4 + 4 = 11 points) covers analysis and theory, Part 2 (Exercises 4-5: 5 + 6 = 11 points) covers algorithm design in pseudocode with analysis. The sample sheets do not state the duration: 150 minutes for Parts 1 and 2 is a proposal. No material is allowed.
Part 3 is a proposal. The real exam also has a programming part. Exercise 6 is a LeetCode-style problem to solve in Java, suggested at 60 minutes at the computer and graded with 10 points for self-assessment only.
Topics: recursive algorithms and the recursion tree, general trees, priority queues and heaps (bottom-up construction, heap sort, k-way merge), loop invariants. Stacks and queues on circular arrays, amortised cost and recurrences solved by substitution are not in the notes of this course, so they were replaced by a loop-invariant exercise (Exercise 4) and by the recursion-tree method checked by induction (Exercise 1). Heaps are numbered from index 0, as in the notes.
Exercise 1 (points 3)
Consider the following recursive algorithm.
Algorithm RecSort(A, n)
Input: array A and integer n ≥ 1; the algorithm works on A[0..n-1]
Output: A[0..n-1] rearranged in non-decreasing order
if (n = 1) then return A;
p ← 0;
for i ← 1 to n-1 do {
if (A[i] > A[p]) then p ← i;
}
swap A[p] and A[n-1];
RecSort(A, n-1);
return AAssume that a call on a prefix of elements costs exactly operations, excluding the recursive call (so the base case costs 1).
(a) Run RecSort(A, 5) on . Write the array after the swap of each call and draw the recursion tree with the cost of each node.
(b) Write the recurrence satisfied by the total cost , guess its solution and prove it by induction on .
(c) Give the tight asymptotic cost of RecSort and say how many activation records are on the stack when the base case is executed.
Show the result
(a) Arrays after the swaps: : ; : ; and : unchanged; : base case. The recursion tree is a chain of 5 nodes with costs (total 15).
(b) , for , solution .
(c) on every instance; activation records (one per call, including the base case).
Show the full solution
(a) In each call the loop finds the position of the maximum of the prefix and moves it to the last position of the prefix; then the algorithm recurses on the prefix without that position (see Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →).
| call | prefix before | max at | array after the swap |
|---|---|---|---|
RecSort(A,5) |
(9) | ||
RecSort(A,4) |
(7) | ||
RecSort(A,3) |
(5), swap with itself | ||
RecSort(A,2) |
(3), swap with itself | ||
RecSort(A,1) |
base case |
Recursion tree (a chain, each node is the only child of the previous one):
RecSort(A,5) cost 5
RecSort(A,4) cost 4
RecSort(A,3) cost 3
RecSort(A,2) cost 2
RecSort(A,1) cost 1 <- base caseThe total cost is the sum of the costs of the nodes: .
(b) The call on elements costs and makes one call on elements, so
Unrolling the recurrence (this is the sum of the costs of the chain) gives , which suggests . Proof by induction on (see Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants → for the scheme, because the step needs only ):
- Base case : .
- Step: assume for some . Then
The step reconnects to the hypothesis by isolating the cost of the first call, . This is Gauss' formula of Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation →.
(c) For every instance of size the recursion tree is the same chain, so the bound holds for all instances: for , hence . The active calls on the stack correspond to a root-to-node path of the recursion tree (see Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →): when the base case runs, the whole chain is active, so activation records are on the stack. The sort needs stack space even though it works in place on .
Typical mistakes. Taking the cost of each node as , which would give (each node scans its whole prefix); writing the recurrence with ; proving the formula without the base case; stating the correct sum but not proving it.
Check: the algorithm, executed in Python with the cost model above on random arrays of length 1 to 199, gives and a sorted array every time.
Exercise 2 (points 4)
Let be the following ordered tree (children listed from left to right):
A
/---------|---------\
B C D
/ | \ |
E F G H
/ \ / | \
I J K L M(a) Give: the depth of ; the height of , of and of ; the number of descendants of and of (a node is a descendant of itself); the number of leaves.
(b) Design a recursive algorithm Stats(T, v, d) that, called on a node of depth , stores in every node of three fields: u.depth, u.height and u.desc (number of descendants of ). Write the initial call.
(c) Analyse the complexity of Stats(T, T.root(), 0) as a function of the number of nodes of .
Show the result
(a) ; , , ; has 6 descendants, has 5; there are 8 leaves ().
(b) Initial call Stats(T, T.root(), 0); the algorithm sets the three fields of each node in a single traversal (code in the solution).
(c) .
Show the full solution
(a) (Trees - Definitions and PropertiesA rooted tree is a hierarchy of nodes under a single root; depth is the distance from the root, height the distance from the farthest leaf, and the height of a tree equals the depth of its deepest leaf.Trees - Definitions and Properties →) Depth counts the steps up to the root: , so . Height is the largest distance from a leaf of the subtree:
- (children and are leaves);
- , so ;
- ;
- , which is the depth of the deepest leaves () as in Proposition 8.3.
has 6 nodes; has 5 nodes. The leaves are the nodes without children: , that is 8.
(b) The depth of a node depends on its ancestors (preorder: it is passed down as a parameter ); height and number of descendants depend on the children (postorder: they are computed after the recursive calls). A single traversal does both, see Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals →.
Algorithm Stats(T, v, d)
Input: node v of T and its depth d in T
Output: for every node u in T_v the fields u.depth, u.height and u.desc are set
v.depth ← d;
v.height ← 0; // value for a leaf
v.desc ← 1; // v is a descendant of itself
foreach w in T.children(v) do {
Stats(T, w, d+1);
v.height ← max{ v.height, 1 + w.height };
v.desc ← v.desc + w.desc;
}Initial call: Stats(T, T.root(), 0). Base case: at a leaf the loop is empty and the fields keep the values and . The children's fields are read right after their call, when they are already correct. Nothing is returned, so no returned value can be lost. On the example the fields are:
| node | A | B | C | D | E | F | G | H | I | J | K | L | M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| depth | 0 | 1 | 1 | 1 | 2 | 2 | 2 | 2 | 3 | 3 | 3 | 3 | 3 |
| height | 3 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
| desc | 13 | 6 | 1 | 5 | 1 | 3 | 1 | 4 | 1 | 1 | 1 | 1 | 1 |
Consistency check: the sum of the desc values is 39, and it equals the sum of over all nodes (each node is counted once for each of its ancestors, itself included).
(c) The recursion tree has exactly one node per node of (one call for each ). The call on costs, excluding the recursive calls, where is the number of children: the loop does iterations of constant cost, and initialisation is constant (the covers the leaves). By Proposition 8.4, , so
The three fields together cost . Computing the depth of every node with the separate algorithm depth would cost in the worst case (a chain), and the height of every node with height the same: the single traversal avoids repeating work.
Typical mistakes. Counting the descendants of as 5 (forgetting that the node is a descendant of itself, by the definition of the notes) or counting the leaves of ; taking the height of as 2; passing instead of to the children; analysing the cost as or without the .
Check: the algorithm run in Python on this tree gives the table above, 13 calls and .
Exercise 3 (points 4)
Let be an array of 9 keys (indices from 0).
(a) Build a min-heap from with the bottom-up approach. Write the array at the end of each iteration and draw the final heap as a tree.
(b) Using the same array, execute the in-place heap sort: write the array after phase A (the bottom-up construction of a max-heap) and after each of the first three iterations of phase B, marking where the sorted part starts.
(c) How many down-heap bubblings does the bottom-up construction perform on 9 keys, and how many up-heap bubblings does the top-down construction perform? Compare the asymptotic costs.
Show the result
(a) After : ; ; ; . Final heap:
2
/ \
6 4
/ \ / \
7 15 9 13
/ \
10 11(b) After phase A: . Phase B: ; ; .
(c) Bottom-up: down-heap bubblings, total . Top-down: up-heap bubblings, total .
Show the full solution
(a) (HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →, bottom-up construction.) With the loop runs for from down to ; the children of are and , and at each step the entry goes down by swapping with its smaller child while it is larger.
| what happens | array after the iteration | |
|---|---|---|
| 3 | , children 6 and 11: swap with 6 | |
| 2 | , children 9 and 13: , no swap | same |
| 1 | , children 6 and 2: swap with 2; now at index 4, a leaf | |
| 0 | , children 2 and 4: swap with 2; at index 1, children 6 and 15: swap with 6; at index 3, children 10 and 11: , stop |
Total 4 swaps. The final tree is the one in the result: every parent is its children (; ; ; ).
(b) (Heap-SortSorting through a priority queue inserts all keys and then removes them in order; with a heap this is HeapSort, which runs in Theta(n log n) and, in its in-place version on a max-heap built bottom-up, uses no extra array.Heap-Sort →) The in-place version works on a max-heap, with children , . Phase A, , swapping with the larger child while smaller:
- : with children 6, 11: swap with 11, giving ;
- : with children 9, 13: swap with 13, giving ;
- : with children 11, 2: no swap;
- : with children 15, 13: swap with 15; at index 1 the children are 11, 2: swap with 11; at index 3 the children are 6, 10: swap with 10. Result (3 swaps).
Phase B, iteration : swap with and restore the max-heap on (down-heap bounded by last):
- : swap with : . Down-heap: 7 with 13 (children 11, 13), then at index 2 with 9 (children 9, 4). Result .
- : swap with : . Down-heap: 6 with 11, then at index 1 with 10 (children 10, 2). Result .
- : swap with : . Down-heap: 4 with 10, then at index 1 with 6 (children 6, 2). Result .
The invariant of the notes holds each time: the part after the bar contains the largest keys in increasing order, the part before the bar is a max-heap of the smaller ones. Continuing to the end, the final array is the sorted one, .
(c) The bottom-up construction does one down-heap bubbling for each internal node, in this case. The top-down construction does up-heap bubblings, one per inserted key from the second. Asymptotically, bottom-up costs because most nodes are near the leaves and cheap (), while top-down costs in the worst case (decreasing input, every key goes to the root). Both are in place.
Typical mistakes. Swapping with the left child instead of the smaller (min-heap) or larger (max-heap) one; starting the bottom-up loop at the last index instead of ; forgetting to restrict the down-heap to last in phase B (it would pull the sorted keys back in); using a min-heap for the in-place sort (the result would be decreasing).
Check: the traces were produced with a Python implementation of the algorithms of the notes (all intermediate arrays above), which also built a valid min-heap and sorted correctly 3000 random arrays of 1 to 40 keys.
Exercise 4 (points 5)
Let be an array of integers. Design an algorithm Separate(S) that rearranges in place so that all negative integers come before all non-negative integers (the order inside each group does not matter). It must use a single loop and extra space. For example may become .
(a) Write the pseudocode.
(b) State a loop invariant that proves the correctness of the algorithm.
(c) Prove the invariant (initialisation, maintenance, conclusion) and the termination of the loop.
(d) Analyse the complexity and give an upper bound on the number of swaps.
Show the result
(a) Two indices from the two ends, one while loop (code in the solution); on the example it gives after 7 iterations and 2 swaps.
(b) Invariant: all entries of are negative, all entries of are non-negative, and contains the not yet examined entries.
(c) Initialisation: both parts are empty. Maintenance by cases. Termination: decreases at each iteration; at the end .
(d) on every instance; at most swaps.
Show the full solution
(a) Idea: keep a negative zone on the left and a non-negative zone on the right, with an unknown zone in the middle that shrinks. Look at the two ends of the unknown zone (see PseudocodePseudocode is the rigorous, free-form way algorithms are specified in this course: a header with name, input and output, then a body that mixes programming constructs with natural language only where it helps.Pseudocode → for the conventions; in a while the control variables are updated by hand).
Algorithm Separate(S)
Input: array S[0..n-1] of n ≥ 0 integers
Output: S rearranged so that all negative entries precede all non-negative ones
i ← 0; j ← n-1;
while (i ≤ j) do {
if (S[i] < 0) then i ← i + 1; // S[i] is already in the right zone
else if (S[j] ≥ 0) then j ← j - 1; // S[j] is already in the right zone
else { // S[i] ≥ 0 and S[j] < 0: both misplaced
swap S[i] and S[j];
i ← i + 1; j ← j - 1;
}
}
return STrace on (state at the end of each iteration, with the new , ):
| iteration | action | |||
|---|---|---|---|---|
| start | 0 | 8 | ||
| 1 | , : decreases | same | 0 | 7 |
| 2 | , : swap | 1 | 6 | |
| 3 | : increases | same | 2 | 6 |
| 4 | , : decreases | same | 2 | 5 |
| 5 | , : swap | 3 | 4 | |
| 6 | : increases | same | 4 | 4 |
| 7 | and : decreases | same | 4 | 3 |
At the end and the result is the array of the statement.
(b) The invariant describes the state at the end of a generic iteration, with being the conjunction of
- every with is negative;
- every with is non-negative;
- , and holds the entries not yet examined (the entries of are always a permutation of the original ones).
Initialisation (, ): the zones and are empty, so properties 1 and 2 hold by vacuity; .
Maintenance. Assume holds at the start of an iteration with .
- : increasing extends the negative zone by a correct entry; 2 is untouched; .
- and : decreasing extends the non-negative zone by a correct entry.
- and : after the swap and , so both zones extend by one correct entry (, ). If the case cannot occur, because and would be contradictory; hence and the new values satisfy .
In every case the invariant holds at the end of the iteration.
Termination. The size of the unknown zone decreases by 1 (first two cases) or by 2 (third case) at each iteration, and the loop runs while it is , so it stops after a finite number of iterations with . Together with this gives .
Conclusion. At the end the unknown zone is empty: is all negative and is all non-negative: holds.
(d) Each iteration costs and removes 1 or 2 entries from the unknown zone, which initially has entries, so the number of iterations is between and : the cost is on every instance. A swap removes two entries from the unknown zone, and it moves one negative entry from the right half and one non-negative entry from the left half: each swap involves one entry of each group, so the swaps are at most . Extra space: two indices and one temporary variable, .
Typical mistakes. An invariant that describes iteration instead of the state after it; forgetting the case and (the algorithm would swap a non-negative entry with another non-negative one); using i < j instead of i ≤ j (the middle entry would not be classified, and for the loop would not run, leaving the entry unchecked); forgetting to update in the swap case, which gives an infinite loop; not stating the permutation property.
Check: in Python, with the invariant asserted at the end of every iteration, 20000 random arrays of 0 to 25 integers satisfy properties 1-3, end with , use between iterations and , and never exceed swaps.
Exercise 5 (points 6)
Let be non-empty arrays of integers, each sorted in non-decreasing order, containing integers in total. Design an algorithm KMerge that returns an array with all the integers of the arrays in non-decreasing order, in time , using a priority queue implemented with a heap (methods insert(key, value), removeMin(), isEmpty()).
(a) Explain the idea and write the pseudocode.
(b) On , , , write the array of the heap (keys only) after the initial insertions and after each of the first three iterations of the main loop, and the output .
(c) Justify the complexity . Why is merging the arrays one after the other worse?
Show the result
(a) The heap holds at most one entry per array: the smallest element not yet output, with its array and position. Repeat: remove the minimum, write it to , insert the next element of the same array (code in the solution).
(b) After the initial insertions: . After iteration 1 (output 1): ; iteration 2 (output 2): ; iteration 3 (output 3): . Final output .
(c) insertions and removals on a heap with at most entries, each : . One-by-one merging costs for arrays of equal length.
Show the full solution
(a) (Priority QueuesA priority queue is a collection of (key, value) entries where removal returns the entry with the smallest key (highest priority), and a list implementation makes either insertion or removal cost linear time.Priority Queues →, HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →) The first element of the merged output is the smallest among the first elements. After outputting an element of , the new candidate from is its successor. So the priority queue holds one candidate per array, and the key is the candidate and the value says where it comes from: the pair = array and position.
Algorithm KMerge(X_0, ..., X_{k-1})
Input: k ≥ 1 non-empty arrays sorted in non-decreasing order, n elements in total (|X_a| = n_a)
Output: array R[0..n-1] with all the elements in non-decreasing order
P ← empty priority queue (heap);
for a ← 0 to k-1 do P.insert(X_a[0], (a, 0));
t ← 0;
while (not P.isEmpty()) do {
e ← P.removeMin();
(a, p) ← e.getValue(); // e came from X_a[p]
R[t] ← e.getKey();
t ← t + 1;
if (p + 1 < n_a) then P.insert(X_a[p+1], (a, p+1)); // next candidate of the same array
}
return RCorrectness (invariant at the end of an iteration). (1) contains the smallest elements of the union, sorted. (2) contains exactly one entry for each array that is not exhausted: its smallest element not yet in . Initially and holds the first element of each array. Maintenance: the removed entry is the smallest of the candidates, and each array is sorted, so every element not yet output is the candidate of its array, which is the removed minimum: it is the smallest of all the remaining elements and goes next in . Inserting the successor from the same array restores (2). When is empty, all arrays are exhausted and . (See Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants →.)
(b) Keys of the heap in array order (min-heap, children of at and ).
- Initial insertions of : ; insert 1, it bubbles above 3: ; insert 4: ; insert 2, it bubbles above 3: .
- Iteration 1:
removeMin()returns 1 (from , position 0). The last key 3 goes to the root, , and bubbles down with its smaller child 2: . Output . Insert the next element of , which is 9: . - Iteration 2:
removeMin()returns 2 (from ). The last key 9 goes to the root, , down with 3: . . Insert 7 (next of ), it bubbles above 9: . - Iteration 3:
removeMin()returns 3 (from ). The last key 9 goes to the root, , down with 4: . . Insert 8 (next of ): .
The remaining iterations give : 11 elements, the 11 keys of the union in order.
(c) (HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps → for the costs.) By the invariant the heap never contains more than entries, so its height is and each insert and removeMin costs . Each element is inserted exactly once and removed exactly once: insertions and removals, and the loop makes iterations with other work. Total (more precisely , so for ). The arrays are non-empty, hence , and the first insertions are part of the . Extra space: for the heap, plus the output .
Merging the arrays one after the other (first with second, the result with the third, ...) copies the accumulated result each time: with arrays of elements the -th merge handles about elements, so the total is , much more than when grows. The heap pays only per element, because it does not rescan the elements already merged. A third approach, concatenating everything and sorting, costs .
Typical mistakes. Inserting all elements first (heap of size , cost and extra space ); inserting the successor before removing (the heap would hold two candidates of the same array, though still correct) or forgetting to insert it at all (elements lost); not storing the array and the position in the value (it is impossible to find the successor); forgetting the test on the last element of an array.
Check: a Python implementation (heap with insert/removeMin as in the notes) reproduces the heap states above and merges correctly 3000 random instances with from 1 to 12. Counting heap comparisons, the ratio between the operations and stays between 1.0 and 1.3 for and up to 65536.
Exercise 6 (points 10)
Part 3, programming in Java (proposal; the 10 points are for self-assessment only). Leaderboard cut (style of the LeetCode problems on priority queues, original text).
An online game publishes a leaderboard that shows only the highest scores. The cut is the -th highest score among all the scores received so far (equal scores count separately: in the 2nd highest is 7). Implement the class below.
public class Leaderboard {
/** k = size of the leaderboard; initial = scores received before the leaderboard started */
public Leaderboard(int k, int[] initial) { ... }
/** registers a new score and returns the k-th highest score among all scores so far */
public int add(int score) { ... }
}Constraints:
- ;
- , with (so at every call of
addthere are at least scores); - , for the initial scores and for the scores passed to
add; - at most calls to
add.
Required complexity: the constructor in ( = initial.length), each call of add in , extra space .
Examples:
k = 3,initial = [4, 5, 8, 2]; callsadd(3),add(5),add(10),add(9),add(4)return4, 5, 5, 8, 8.k = 1,initial = []; callsadd(-3),add(-1),add(-5)return-3, -1, -1.k = 2,initial = [7, 7, 7]; callsadd(7),add(1)return7, 7.
Show the result
Outputs of the three examples: 4 5 5 8 8; -3 -1 -1; 7 7. Solution: a min-heap that keeps only the highest scores; the cut is its root.
Show the full solution
Idea. Sorting all the scores at every call costs per call: too slow. Only the highest scores matter, and among them the smallest is the answer. A min-heap (HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →, Priority QueuesA priority queue is a collection of (key, value) entries where removal returns the entry with the smallest key (highest priority), and a list implementation makes either insertion or removal cost linear time.Priority Queues →) of size at most gives exactly that: its root min() is the smallest of the highest scores, i.e. the -th highest. This is the top- scheme of Priority QueuesA priority queue is a collection of (key, value) entries where removal returns the entry with the smallest key (highest priority), and a list implementation makes either insertion or removal cost linear time.Priority Queues → (the entries are the scores, with no stored value).
- If the heap has fewer than entries, insert the score.
- Otherwise, if the score is strictly larger than the root, it beats the current -th:
removeMin()theninsert. If it is not larger, it is not among the highest and is ignored (a score equal to the root changes nothing for the -th highest value).
Each score costs (the heap never exceeds entries), so the constructor costs , add costs and the space is . In Java java.util.PriorityQueue is a heap (see Heap-SortSorting through a priority queue inserts all keys and then removes them in order; with a heap this is HeapSort, which runs in Theta(n log n) and, in its in-place version on a max-heap built bottom-up, uses no extra array.Heap-Sort →); offer is insert, peek is min() and poll is removeMin().
import java.util.PriorityQueue;
public class Leaderboard {
private final int k;
private final PriorityQueue<Integer> top = new PriorityQueue<>(); // min-heap with the k highest scores
/** Builds the leaderboard from the initial scores. O(m log k) for m initial scores. */
public Leaderboard(int k, int[] initial) {
this.k = k;
for (int s : initial) offerKeepingK(s);
}
/** Registers a new score and returns the k-th highest score so far. O(log k). */
public int add(int score) {
offerKeepingK(score);
return top.peek(); // root of the min-heap = smallest of the k highest = k-th highest
}
private void offerKeepingK(int s) {
if (top.size() < k) {
top.offer(s);
} else if (s > top.peek()) { // s beats the current k-th score
top.poll(); // the old k-th score leaves the leaderboard
top.offer(s);
} // otherwise s is not among the k highest: ignore it
}
}Trace of example 1 (): after the constructor the heap holds the three highest of , i.e. (the 2 was ignored when the heap was full and 2 is below the root 4). add(3): , ignored, root 4, answer 4. add(5): , the 4 leaves: , answer 5. add(10): : , answer 5. add(9): , answer 8. add(4): , ignored, answer 8. Output 4 5 5 8 8, as expected. Example 2: with the heap holds the maximum: , then replaces it, then is ignored: -3 -1 -1. Example 3: heap , add(7): is false, ignored, answer 7; add(1) ignored, answer 7: 7 7.
Edge cases. (the heap is the running maximum); empty initial (the first add has at least scores only if , guaranteed by the constraint ); negative and repeated scores (the comparison s > top.peek() is strict: a repeated score is already represented, nothing changes); equal to the number of scores (the cut is the minimum, nothing is ever removed).
Typical mistakes. Using a max-heap (the root would be the highest score, not the -th); letting the heap grow beyond (time and space and the root would be wrong); using >= and removing the root on ties (harmless for the answer but wasted work); calling peek() on an empty heap (excluded by the constraints); sorting the array at each call.
Verification (run for real). The code was compiled and run with JDK 21: the three examples print 4 5 5 8 8, -3 -1 -1, 7 7. A battery of 20000 random instances (with from 1 to 6, up to 7 initial and 8 added scores in , all constraints respected, many repeated values) gave 90508 calls whose result always coincides with the brute force that sorts all the scores and takes the -th largest. A run with the maximum sizes (, initial scores, calls to add) takes about 3 ms.
Self-assessment grid
| Exercise | Points | What must be there for full marks | Typical mistakes |
|---|---|---|---|
| 1 | 3 | (a) correct arrays after each swap and chain of 5 nodes with costs 5, 4, 3, 2, 1 (1); (b) recurrence with and induction proof of with base and step (1.5); (c) for every instance and activation records (0.5) | cost per node; missing base case; formula not proved |
| 2 | 4 | (a) depth 3, heights 1, 2, 3, descendants 6 and 5, 8 leaves (1); (b) correct postorder/preorder algorithm with , base case at leaves and initial call (2); (c) one call per node, cost and , so (1) | forgetting that a node is its own descendant; not incremented; cost stated without or without Proposition 8.4 |
| 3 | 4 | (a) four correct arrays and the final tree (1.5); (b) max-heap after phase A and the three correct iterations of phase B with the sorted part marked (2); (c) 4 versus 8 bubblings and versus (0.5) | wrong child chosen; wrong starting index; phase B without the bound last; min-heap used for the in-place sort |
| 4 | 5 | (a) correct single-loop pseudocode with the three cases (2); (b) invariant with both zones and the permutation property (1); (c) initialisation, maintenance of the three cases, termination and conclusion (1.5); (d) and at most swaps (0.5) | invariant on iteration instead of the state after it; i < j; missing case with two non-negative ends |
| 5 | 6 | (a) idea, correct pseudocode with in the value and the test (3); (b) correct heap states and output (1); (c) heap size , insertions and removals, , and the comparison with one-by-one merging (2) | heap of size ; losing the successor; analysis without the size of the heap |
| 6 | 10 (proposal) | correct class with a min-heap of size (6); the three examples give the expected outputs (2); complexity per call and space justified (2) | max-heap; heap larger than ; sorting at each call |