Salta al contenuto
Note per Studenti Data Structures and Algorithms - Official Sample Exam 5 Report

Data Structures and Algorithms - Official Sample Exam 5

Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.

In questa pagina 6

Official sample of a written exam, one of the samples distributed by the equivalent Italian course of Data Structures and Algorithms (Dati e Algoritmi) for Engineering at the University of Padua, translated into English. It is not a dated exam session. The sheet has two parts (Part 1: exercises 1-3, Part 2: exercises 4-5), with the points per question: total 22 points; the duration and the allowed material are not stated on the sheet. The official solution is not public: every answer below was derived and checked (with Python programs where the answer can be computed). The third part of the real exam (programming) is not part of this sheet.

Heap convention: as in 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 → and 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 →, a heap is a min-heap (the smallest key is at the root).

Exercise 1 (points 3)

Define as a computational problem Π\Pi the following problem: given an array of integers, determine the number of cells whose value is greater than or equal to a given integer kk.

Show the result

I={(A,k):A array of integers,k∈Z}\mathcal{I}=\{(A,k): A \text{ array of integers}, k\in\mathbb{Z}\}, S=NS=\mathbb{N}, Π={((A,k),s):s=∣{j:A[j]≥k}∣}\Pi=\{((A,k),s): s=|\{j: A[j]\ge k\}|\}. Example: ((⟨5,1,7,7,3⟩,5),3)∈Π((\langle 5,1,7,7,3\rangle,5),3)\in\Pi.

Show the full solution

A computational problem is a relation Π⊆I×S\Pi\subseteq\mathcal{I}\times S between instances and solutions (see Computational Problems, Algorithms and Models of ComputationA computational problem is a relation between instances and solutions, an algorithm is a finite procedure that computes one valid solution for each instance in a model of computation (RAM), and a data structure organises the data the algorithm works on.Computational Problems, Algorithms and Models of Computation →). Three things must be said: the instances, the solutions, the relation.

  • Instances. The input has two parts: the array and the threshold kk. So an instance is a pair (A,k)(A,k) with A=⟨A[0],…,A[n−1]⟩A=\langle A[0],\dots,A[n-1]\rangle an array of integers (n≥0n\ge 0) and k∈Zk\in\mathbb{Z}. Forgetting kk among the data is the commonest mistake: with only AA the question has no meaning.
  • Solutions. The answer is a count: S=N={0,1,2,… }S=\mathbb{N}=\{0,1,2,\dots\} (0 is possible, if no cell reaches kk).
  • Relation. Π={((A,k),s)∈I×S  :  s=∣{ j:0≤j<n, A[j]≥k }∣}.\Pi=\{((A,k),s)\in\mathcal{I}\times S \;:\; s=\big|\{\,j : 0\le j<n,\ A[j]\ge k\,\}\big|\}. Here the solution of every instance is unique, so Π\Pi is a function; the requirement "every instance has at least one solution" holds because the count always exists.

Checks: ((⟨5,1,7,7,3⟩,5),3)∈Π((\langle 5,1,7,7,3\rangle,5),3)\in\Pi (cells 5, 7, 7); ((⟨5,1,7,7,3⟩,5),2)∉Π((\langle 5,1,7,7,3\rangle,5),2)\notin\Pi; ((⟨1,2⟩,9),0)∈Π((\langle 1,2\rangle,9),0)\in\Pi; the empty array always gives 0. Note that repeated values are counted once per cell (the two 7s count twice): "number of cells", not of distinct values. A program counting the cells on the examples above confirmed these values.

Exercise 2 (points 4)

Consider the preorder traversal of a tree TT with nn nodes performed by invoking preorder(T,T.root()). For each node u∈Tu\in T let cuc_u be the number of children of uu and tut_u the cost of visiting uu. Recall that ∑u∈Tcu=n−1\sum_{u\in T}c_u=n-1.

(a) Say how many nodes the recursion tree associated with preorder(T,T.root()) has, and what the cost of each node is.

(b) Let tu∈Θ(log⁡n)t_u\in\Theta(\log n) for every u∈Tu\in T. Using the previous point, determine the complexity of preorder(T,T.root()).

Show the result

(a) The recursion tree has exactly nn nodes (one call per node of TT); the node of uu costs Θ(1+cu+tu)\Theta(1+c_u+t_u).

(b) Θ(nlog⁡n)\Theta(n\log n).

Show the full solution

(a) In 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 → the traversal is analysed through its 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 →):

(b) The total cost is the sum of the costs of the nn nodes: T(n)=Θ(∑u∈T(1+cu+tu))=Θ(∑u∈T1+∑u∈Tcu+∑u∈Ttu).T(n)=\Theta\Big(\sum_{u\in T}(1+c_u+t_u)\Big)=\Theta\Big(\sum_{u\in T}1+\sum_{u\in T}c_u+\sum_{u\in T}t_u\Big).

  • ∑u1=n\sum_{u}1=n;
  • ∑ucu=n−1\sum_u c_u=n-1 (given: every node except the root is the child of exactly one node);
  • tu∈Θ(log⁡n)t_u\in\Theta(\log n) for each of the nn nodes, so ∑utu∈Θ(nlog⁡n)\sum_u t_u\in\Theta(n\log n) (each term is between alog⁡na\log n and blog⁡nb\log n with a,b>0a,b>0, hence the sum is between a nlog⁡na\,n\log n and b nlog⁡nb\,n\log n).

Therefore T(n)=Θ(n+(n−1)+nlog⁡n)=Θ(nlog⁡n)T(n)=\Theta(n+(n-1)+n\log n)=\Theta(n\log n), since 2n−1∈O(nlog⁡n)2n-1\in O(n\log n) for n≥2n\ge 2 and the dominant term is nlog⁡nn\log n. The same cost would be obtained for postorder (same recursion tree, same cost per node).

Typical mistakes: saying the cost is Θ(n)\Theta(n) because "a traversal is linear" (true only if tu=O(1)t_u=O(1): the general formula is Θ(n+∑utu)\Theta(n+\sum_u t_u)); or multiplying by the height of TT instead of summing over the nodes.

Check: a program that builds random trees with n=10,100,1000,4000n=10,100,1000,4000, runs the preorder counting the work 1+cu+⌈log⁡2n⌉1+c_u+\lceil\log_2 n\rceil per call, confirmed exactly nn calls, ∑cu=n−1\sum c_u=n-1, and total cost over nlog⁡2nn\log_2 n equal to 1.78, 1.35, 1.20, 1.17 (converging to a constant slightly above 1, as expected for Θ(nlog⁡n)\Theta(n\log n)).

Exercise 3 (points 4)

Consider the array of entries P=[(10,∗),(8,∗),(6,∗),(7,∗),(5,∗),(2,∗)]P=[(10,*),(8,*),(6,*),(7,*),(5,*),(2,*)] and the top-down approach to build a heap from PP. Show the tree associated with the array at the end of each iteration of the top-down approach. (It is enough to show the keys of the entries.)

Show the result

Keys at the end of each iteration (the array after the iteration, restricted to P[0..j]P[0..j]):

  • j=1j=1: [8,10][8,10]
  • j=2j=2: [6,10,8][6,10,8]
  • j=3j=3: [6,7,8,10][6,7,8,10]
  • j=4j=4: [5,6,8,10,7][5,6,8,10,7]
  • j=5j=5: [2,6,5,10,7,8][2,6,5,10,7,8] (final heap)
Show the full solution

Top-down construction (Solution 1 in 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 j=1,…,n−1j=1,\dots,n-1 the entry P[j]P[j] is inserted into the heap P[0..j−1]P[0..j-1] with an up-heap bubbling: while it has a parent with a larger key (parent of index ii is ⌊(i−1)/2⌋\lfloor (i-1)/2\rfloor) the two are swapped. Invariant at the end of iteration jj: P[0..j]P[0..j] is a heap and P[j+1..n−1]P[j+1..n-1] is still in the original order. Here n=6n=6, so there are 5 iterations (j=1,…,5j=1,\dots,5); before starting, P[0]=10P[0]=10 alone is a heap.

Initial array, read as a complete binary tree (level order), is not a heap (10 is larger than its children):

        10
       /  \
      8    6
     / \  /
    7  5 2

In every drawing below the nodes outside P[0..j]P[0..j] are not yet part of the heap and are not drawn.

j=1j=1: P[1]=8P[1]=8 is a child of the root 1010; 10>810>8, swap. Array [8,10][8,10].

    8
   /
  10

j=2j=2: 66 is the right child of the root 88; 8>68>6, swap. Array [6,10,8][6,10,8].

    6
   / \
  10  8

j=3j=3: 77 becomes the left child of 1010 (index 3, parent index 1); 10>710>7, swap; then the parent is the root 6≤76\le 7: stop. Array [6,7,8,10][6,7,8,10].

      6
     / \
    7   8
   /
  10

j=4j=4: 55 becomes the right child of the node 77 (index 4, parent index 1); 7>57>5, swap; the new parent is the root 6>56>5, swap again. Two swaps. Array [5,6,8,10,7][5,6,8,10,7].

      5
     / \
    6   8
   / \
  10  7

j=5j=5: 22 becomes the left child of 88 (index 5, parent index 2); 8>28>2, swap; then the root 5>25>2, swap again. Array [2,6,5,10,7,8][2,6,5,10,7,8].

      2
     / \
    6   5
   / \  /
  10  7 8

The final array [2,6,5,10,7,8][2,6,5,10,7,8] is a heap: the heap-order property holds for each node (children of 22: 6,56,5; of 66: 10,710,7; of 55: 88) and the tree is complete.

Typical mistakes: showing only the final tree (the exercise asks for the tree after each iteration); using the bottom-up approach (a different algorithm, which here would give [2,5,6,7,8,10][2,5,6,7,8,10]); treating the heap as a max-heap; stopping the bubbling after one swap.

Check: a program implementing the top-down construction on PP reproduced all five arrays above and the number of swaps per iteration (1,1,1,2,2)(1,1,1,2,2), and checked the heap-order property of the final array.

Exercise 4 (points 5)

Let TT be a binary search tree that implements a map whose entries are pairs (t,it)(t,i_t), where tt (the key) is an instant of time in which an earthquake occurred, and iti_t (the value) is the intensity of the earthquake. Every node v∈Tv\in T has a field v.max holding the maximum intensity of the earthquakes represented by the entries of TvT_v (the subtree rooted at vv).

(a) Design a recursive algorithm CheckGG that, given a time tt and an intensity value ii, returns yes if there was an earthquake of intensity ≥i\ge i at a time ≥t\ge t, and no otherwise. State clearly the input and the output of the algorithm.

(b) Analyse the complexity of the algorithm of the previous point.

Show the result

(a) CheckGG(v,t,i), initial call CheckGG(T.root(),t,i). If vv is null return no. If v.key<tv.\text{key}<t recurse on the right child only. Otherwise (v.key≥tv.\text{key}\ge t) return yes if the intensity of vv is ≥i\ge i, or if the right child exists and its max is ≥i\ge i; else recurse on the left child only. One recursive call at most per call.

(b) O(h)O(h), with hh the height of TT (at most h+2h+2 calls, constant work each); O(log⁡n)O(\log n) if TT is balanced, O(n)O(n) in the worst case of a degenerate tree.

Show the full solution

Binary search tree property (see Trees in CA tree is a set of nodes with a root and a unique predecessor per node; in C a binary search tree uses a struct with two child pointers and recursive search, insertion at a leaf, three-case deletion and four traversals.Trees in C → and Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →): all keys in the left subtree of a node are smaller than its key and all keys in the right subtree are larger; keys of a map are distinct. A traversal of the whole tree would be correct but Θ(n)\Theta(n); the field max allows us to follow one path only.

Which entries have time ≥t\ge t in TvT_v? Let kk be the key of vv.

  • If k<tk<t: vv and its whole left subtree (keys <k<k) have time <t<t; only the right subtree can contain valid entries. Go right.
  • If k≥tk\ge t: vv itself has time ≥t\ge t, and every entry of the right subtree too (keys >k≥t>k\ge t): all of them qualify as time. The left subtree has entries with time both below and above tt: it must be explored.

So for k≥tk\ge t the entries to examine are: vv, the whole right subtree (answered in O(1)O(1) by v.right.max, that is the maximum of all their intensities), and a part of the left subtree.

Algorithm.

Algorithm CheckGG(v, t, i)
Input:  v = a node of the search tree (or null), t = a time, i = an intensity;
        v.key = time of the entry of v, v.value = its intensity, v.max as in the text
Output: yes if T_v contains an entry (time, intensity) with time >= t and intensity >= i;
        no otherwise
if v = null then return no                          // base case: empty subtree
if v.key < t then
    return CheckGG(v.right, t, i)                   // v and its left subtree are too early
else {                                              // v.key >= t
    if v.value >= i then return yes                 // v itself qualifies
    if v.right != null AND v.right.max >= i then
        return yes                                  // all keys of the right subtree are > v.key >= t
    return CheckGG(v.left, t, i)                    // only the left subtree remains
}

Initial call: CheckGG(T.root(), t, i); the value returned by the recursive call is returned (not lost), as required for recursive algorithms in 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 →.

Correctness (induction on the number of nodes of TvT_v). Base: v=v= null has no entries, no is right. Step: assume the claim for the subtrees of vv.

  • v.key<tv.\text{key}<t: the entries of TvT_v with time ≥t\ge t are all in the right subtree, so the answer for TvT_v is the answer for the right subtree, correct by hypothesis.
  • v.key≥tv.\text{key}\ge t: if vv has intensity ≥i\ge i then vv is a witness and yes is correct. If the right child has max ≥i\ge i, some entry of the right subtree has intensity ≥i\ge i and, having key >v.key≥t>v.\text{key}\ge t, time ≥t\ge t: yes is correct. Otherwise neither vv nor any entry of the right subtree is a witness, so a witness exists in TvT_v iff it exists in the left subtree: correct by hypothesis.

(b) Complexity. Each call does a constant number of operations (comparisons and field reads) and makes at most one recursive call, on a child of vv. The recursion tree is therefore a path from the root, going down by one level at each call: at most h+1h+1 calls on nodes plus possibly one on null, that is at most h+2h+2 calls, each Θ(1)\Theta(1). The total is O(h)O(h). In a balanced tree h=Θ(log⁡n)h=\Theta(\log n), giving O(log⁡n)O(\log n); in the worst case h=n−1h=n-1 and the cost is O(n)O(n). In every case it is not worse than the Θ(n)\Theta(n) of a full traversal.

Typical mistakes: recursing on both children whenever v.key≥tv.\text{key}\ge t (correct, but in the worst case it visits many nodes: no gain over a traversal); forgetting that the right subtree is entirely recent when v.key≥tv.\text{key}\ge t (and thus not using max of the right child); using v.max of the node itself to answer yes (it also counts entries with time <t<t); forgetting null children.

Check: the algorithm was implemented in Python on binary search trees (inserted in random order, max maintained) and compared with the brute-force definition on 60000 random queries over 3000 random trees of up to 40 entries (including empty trees and tt outside the range of the keys): all answers agreed and the number of calls never exceeded h+2h+2. Worked example on the tree with root (50,3)(50,3), left subtree (30,6)(30,6) with children (20,1)(20,1), (40,5)(40,5), right subtree (70,2)(70,2) with children (60,4)(60,4), (80,7)(80,7) (the max values are 7 at the root, 6 at 30, 7 at 70): CheckGG(root,45,6) = yes (found at the root through the right child, whose max is 7); CheckGG(root,65,8) = no after 4 calls (the root goes right because 50<6550<65; at 70 the right child has max 7 <8<8 and 70 has intensity 2, so it goes left; 60 is before 65, so it goes right to null).

Exercise 5 (points 6)

Let S1[0..n−1]S_1[0..n-1] and S2[0..n−1]S_2[0..n-1] be two sorted arrays of nn integer keys each. In each array the keys are distinct, but a key may appear in both arrays.

(a) Design an algorithm CountNeg, containing a single loop, that determines the number of distinct negative keys appearing in S1S_1 and/or S2S_2. For example, if S1=[−3,−2,0,34]S_1=[-3,-2,0,34] and S2=[−7,−2,34,45]S_2=[-7,-2,34,45] the algorithm returns 3 (distinct negative keys: −7,−3,−2-7,-3,-2). To get full marks the algorithm must use constant space, apart from S1S_1 and S2S_2.

(b) Specify a suitable invariant to be used to prove the correctness of the algorithm.

Show the result

(a) A merge-like scan with two indices i,ji,j and a counter cc: while some array still has a negative key at its current position, count the smaller of the two current negative keys and advance the index (or both indices, if the keys are equal). Returns 3 on the example. Time Θ(n)\Theta(n) in the worst case (at most 2n2n iterations), O(1)O(1) extra space.

(b) At the start of each iteration (and at the end of the loop): let U={S1[0],…,S1[i−1]}∪{S2[0],…,S2[j−1]}U=\{S_1[0],\dots,S_1[i-1]\}\cup\{S_2[0],\dots,S_2[j-1]\}. Then (1) every element of UU is negative; (2) every key of S1[i..n−1]S_1[i..n-1] and of S2[j..n−1]S_2[j..n-1] is greater than every element of UU; (3) c=∣U∣c=|U| (the number of distinct elements of UU).

Show the full solution

Idea. The arrays are sorted, so the negative keys of each form a prefix. It is the scheme of the merge of two sorted sequences: with two indices we read the keys of both arrays in increasing order. At each step we look at the two current keys; the smaller one is a new negative key to count (it cannot have been counted before, because it is larger than everything already consumed). If the two current keys are equal it is the same key: count it once and advance both. We stop as soon as no array has a negative key left in the current position. No auxiliary array is needed (constant space), and a key present in both arrays is counted once.

Algorithm.

Algorithm CountNeg(S1, S2, n)
Input:  two sorted arrays S1[0..n-1], S2[0..n-1] of integers; keys distinct within each array
Output: the number of distinct negative keys that appear in S1 and/or S2
i <- 0; j <- 0; c <- 0
while (i < n AND S1[i] < 0) OR (j < n AND S2[j] < 0) do {
    if (j = n OR S2[j] >= 0) then          // only S1 has a negative key at the current position
        i <- i + 1
    else if (i = n OR S1[i] >= 0) then     // only S2 has a negative key at the current position
        j <- j + 1
    else if S1[i] < S2[j] then
        i <- i + 1
    else if S1[i] > S2[j] then
        j <- j + 1
    else {                                 // S1[i] = S2[j]: same key, counted once
        i <- i + 1
        j <- j + 1
    }
    c <- c + 1
}
return c

In the first branch, the condition of the while guarantees that S1S_1 has a negative key at position ii (since S2S_2 has none); in the second, S2S_2 has one by the same reasoning, because the first test failed. In the last three branches both heads are negative. Every iteration moves ii or jj (or both) forward and each of i,ji,j is at most nn, so the loop ends after at most 2n2n iterations: termination. Cost Θ(n)\Theta(n) in the worst case (for example if all the keys of both arrays are negative and distinct), constant work per iteration; only i,j,ci,j,c are used: constant space. On the example: S1[0]=−3>S2[0]=−7S_1[0]=-3>S_2[0]=-7, so jj advances (c=1c=1, key −7-7); then −3<−2-3<-2 and ii advances (c=2c=2, key −3-3); then −2=−2-2=-2 and both advance (c=3c=3, key −2-2); then S1[2]=0≥0S_1[2]=0\ge 0 and S2[2]=34≥0S_2[2]=34\ge 0: stop, return 3.

(b) Invariant (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 →). Let Ui,j={S1[0..i−1]}∪{S2[0..j−1]}U_{i,j}=\{S_1[0..i-1]\}\cup\{S_2[0..j-1]\} be the set of keys already consumed. At the start of every iteration (after any number of iterations, including zero):

  1. all the elements of Ui,jU_{i,j} are negative;
  2. every key of S1[i..n−1]S_1[i..n-1] and of S2[j..n−1]S_2[j..n-1] is strictly greater than every element of Ui,jU_{i,j};
  3. c=∣Ui,j∣c=|U_{i,j}|.

Initialisation. i=j=0i=j=0: U=∅U=\emptyset, c=0c=0. All three hold (vacuously for 1 and 2).

Maintenance. Assume the invariant before an iteration in which the loop condition holds, and let mm be the key consumed: m=S1[i]m=S_1[i] in the first and third branches, m=S2[j]m=S_2[j] in the second and fourth, the common value in the fifth. In each case mm is the minimum among the keys at the current positions that are negative, and it is negative. Then:

  • mm is not in Ui,jU_{i,j}, by property 2 (mm is greater than all of UU), and in the branches where both heads are consumed the two heads are equal, so ∣U∣|U| grows by exactly 1, the same as cc: property 3. Property 1 holds because m<0m<0.
  • Property 2: in an array that advances, the remaining keys are larger than the consumed head mm (strictly increasing). In an array that does not advance, the head is ≥m\ge m (since mm is the smaller negative head, and a non-negative head is larger than m<0m<0), and it is not equal to mm (otherwise that array would have advanced too: fifth branch), so it is >m>m, and so are the following keys. All the keys left are therefore greater than mm and, by the hypothesis, greater than the old elements of UU.

Termination. The loop ends when (i=n(i=n or S1[i]≥0)S_1[i]\ge 0) and (j=n(j=n or S2[j]≥0)S_2[j]\ge 0). Since the arrays are sorted, every key at position ≥i\ge i in S1S_1 is ≥S1[i]≥0\ge S_1[i]\ge 0 (or there are none), and the same holds for S2S_2: all the negative keys are in the consumed prefixes, so by property 1 Ui,jU_{i,j} is exactly the set of negative keys of S1∪S2S_1\cup S_2. By property 3, cc is its number of elements: the value returned is correct.

Typical mistakes: using two loops (one scanning each array) or a nested loop to look for the common keys (the exercise requires one loop); allocating a set or an array to remove duplicates (not constant space); counting a key twice when it is in both arrays; forgetting the case where one array is exhausted (i=ni=n or j=nj=n) and reading S[n]S[n]; not stating what the invariant says about the keys not yet read (property 2), which is what makes duplicates impossible.

Check: the algorithm was run in Python on the example of the text (it returns 3) and on 20000 random pairs of sorted arrays with distinct keys (length 0 to 12): the result always equals the number of distinct negative keys computed with a set, and the number of iterations never exceeded 2n2n; with all keys negative and distinct (2 arrays of n=10,100,1000n=10,100,1000 keys) it performs exactly 2n2n iterations.

Self-assessment grid
Exercise Points What is needed for full marks Typical mistakes
1 3 Instances (array and kk), solution set (non-negative integers) and the relation Π\Pi stated precisely Omitting kk from the instance; describing an algorithm instead of the relation; counting distinct values instead of cells
2 4 (a) nn nodes, one per node of TT; cost Θ(1+cu+tu)\Theta(1+c_u+t_u) per node. (b) Sum over nodes with ∑cu=n−1\sum c_u=n-1 and ∑tu=Θ(nlog⁡n)\sum t_u=\Theta(n\log n), result Θ(nlog⁡n)\Theta(n\log n) Answering Θ(n)\Theta(n); forgetting the +1+1; multiplying by the height; no justification of the sums
3 4 The tree (or array) after each of the 5 iterations, correct swaps with the parent, final array [2,6,5,10,7,8][2,6,5,10,7,8] Showing only the final result; bottom-up instead of top-down; stopping bubbling too early; max-heap
4 5 Correct recursion on one child only; input/output stated; use of max of the right child when v.key≥tv.\text{key}\ge t; base case; O(h)O(h) with justification Recursing on both children; wrong use of v.max; missing base case; losing the returned value; complexity Θ(n)\Theta(n)
5 6 A single loop, constant space, duplicates counted once, empty arrays handled; invariant with the three properties (consumed keys negative, rest larger, counter = their number) and its proof Two loops or a set; double counting; reading out of bounds; invariant that says nothing about the unread keys