Salta al contenuto
Note per Studenti Data Structures and Algorithms - Mock Exam 2 Report

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 A

Assume that a call on a prefix of mm elements costs exactly mm operations, excluding the recursive call (so the base case m=1m = 1 costs 1).

(a) Run RecSort(A, 5) on A=[7,3,9,1,5]A = [7, 3, 9, 1, 5]. 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 T(n)T(n), guess its solution and prove it by induction on nn.

(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: n=5n=5: [7,3,5,1,9][7,3,5,1,9]; n=4n=4: [1,3,5,7,9][1,3,5,7,9]; n=3n=3 and n=2n=2: unchanged; n=1n=1: base case. The recursion tree is a chain of 5 nodes with costs 5,4,3,2,15, 4, 3, 2, 1 (total 15).

(b) T(1)=1T(1) = 1, T(n)=T(n−1)+nT(n) = T(n-1) + n for n≥2n \ge 2, solution T(n)=n(n+1)2T(n) = \dfrac{n(n+1)}{2}.

(c) Θ(n2)\Theta(n^2) on every instance; nn activation records (one per call, including the base case).

Show the full solution

(a) In each call the loop finds the position pp 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 pp array after the swap
RecSort(A,5) [7,3,9,1,5][7,3,9,1,5] p=2p = 2 (9) [7,3,5,1,9][7,3,5,1,9]
RecSort(A,4) [7,3,5,1][7,3,5,1] p=0p = 0 (7) [1,3,5,7,9][1,3,5,7,9]
RecSort(A,3) [1,3,5][1,3,5] p=2p = 2 (5), swap with itself [1,3,5,7,9][1,3,5,7,9]
RecSort(A,2) [1,3][1,3] p=1p = 1 (3), swap with itself [1,3,5,7,9][1,3,5,7,9]
RecSort(A,1) base case [1,3,5,7,9][1,3,5,7,9]

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 case

The total cost is the sum of the costs of the nodes: 5+4+3+2+1=155 + 4 + 3 + 2 + 1 = 15.

(b) The call on nn elements costs nn and makes one call on n−1n-1 elements, so

T(1)=1,T(n)=T(n−1)+n(n≥2).T(1) = 1, \qquad T(n) = T(n-1) + n \quad (n \ge 2).

Unrolling the recurrence (this is the sum of the costs of the chain) gives T(n)=n+(n−1)+⋯+2+1T(n) = n + (n-1) + \dots + 2 + 1, which suggests T(n)=n(n+1)2T(n) = \dfrac{n(n+1)}{2}. Proof by induction on n≥1n \ge 1 (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, k=0k = 0 because the step needs only T(n)T(n)):

  • Base case n=1n = 1: T(1)=1=1⋅22T(1) = 1 = \dfrac{1 \cdot 2}{2}.
  • Step: assume T(n)=n(n+1)2T(n) = \dfrac{n(n+1)}{2} for some n≥1n \ge 1. Then T(n+1)=T(n)+(n+1)=n(n+1)2+(n+1)=(n+1)(n+2)2.T(n+1) = T(n) + (n+1) = \frac{n(n+1)}{2} + (n+1) = \frac{(n+1)(n+2)}{2}.

The step reconnects T(n+1)T(n+1) to the hypothesis by isolating the cost of the first call, n+1n+1. 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 nn the recursion tree is the same chain, so the bound holds for all instances: n2/2≤n(n+1)2≤n2n^2/2 \le \dfrac{n(n+1)}{2} \le n^2 for n≥1n \ge 1, hence tRecSort(n)∈Θ(n2)t_{\text{RecSort}}(n) \in \Theta(n^2). 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 nn activation records are on the stack. The sort needs Θ(n)\Theta(n) stack space even though it works in place on AA.

Typical mistakes. Taking the cost of each node as Θ(1)\Theta(1), which would give Θ(n)\Theta(n) (each node scans its whole prefix); writing the recurrence with T(n−1)+1T(n-1) + 1; proving the formula without the base case; stating the correct sum n+⋯+1n + \dots + 1 but not proving it.

Check: the algorithm, executed in Python with the cost model above on random arrays of length 1 to 199, gives T(n)=n(n+1)/2T(n) = n(n+1)/2 and a sorted array every time.

Exercise 2 (points 4)

Let TT 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 JJ; the height of FF, of DD and of TT; the number of descendants of BB and of DD (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 vv of depth dd, stores in every node uu of TvT_v three fields: u.depth, u.height and u.desc (number of descendants of uu). Write the initial call.

(c) Analyse the complexity of Stats(T, T.root(), 0) as a function of the number nn of nodes of TT.

Show the result

(a) depth(J)=3\text{depth}(J) = 3; height(F)=1\text{height}(F) = 1, height(D)=2\text{height}(D) = 2, height(T)=3\text{height}(T) = 3; BB has 6 descendants, DD has 5; there are 8 leaves (C,E,G,I,J,K,L,MC, E, G, I, J, K, L, M).

(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) Θ(n)\Theta(n).

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: J→F→B→AJ \to F \to B \to A, so depth(J)=3\text{depth}(J) = 3. Height is the largest distance from a leaf of the subtree:

  • height(F)=1+max⁡{0,0}=1\text{height}(F) = 1 + \max\{0, 0\} = 1 (children II and JJ are leaves);
  • height(H)=1\text{height}(H) = 1, so height(D)=1+height(H)=2\text{height}(D) = 1 + \text{height}(H) = 2;
  • height(B)=1+max⁡{0,1,0}=2\text{height}(B) = 1 + \max\{0, 1, 0\} = 2;
  • height(T)=height(A)=1+max⁡{2,0,2}=3\text{height}(T) = \text{height}(A) = 1 + \max\{2, 0, 2\} = 3, which is the depth of the deepest leaves (I,J,K,L,MI, J, K, L, M) as in Proposition 8.3.

TB={B,E,F,G,I,J}T_B = \{B, E, F, G, I, J\} has 6 nodes; TD={D,H,K,L,M}T_D = \{D, H, K, L, M\} has 5 nodes. The leaves are the nodes without children: C,E,G,I,J,K,L,MC, E, G, I, J, K, L, M, that is 8.

(b) The depth of a node depends on its ancestors (preorder: it is passed down as a parameter dd); 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 00 and 11. 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 depth(u)+1\text{depth}(u) + 1 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 TT (one call for each uu). The call on uu costs, excluding the recursive calls, Θ(cu+1)\Theta(c_u + 1) where cuc_u is the number of children: the loop does cuc_u iterations of constant cost, and initialisation is constant (the +1+1 covers the leaves). By Proposition 8.4, ∑ucu=n−1\sum_u c_u = n - 1, so

Θ(∑u∈T(cu+1))=Θ(n−1+n)=Θ(n).\Theta\Big(\sum_{u \in T}(c_u + 1)\Big) = \Theta(n - 1 + n) = \Theta(n).

The three fields together cost Θ(n)\Theta(n). Computing the depth of every node with the separate algorithm depth would cost Θ(n2)\Theta(n^2) 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 BB as 5 (forgetting that the node is a descendant of itself, by the definition of the notes) or counting the leaves of TBT_B; taking the height of FF as 2; passing dd instead of d+1d+1 to the children; analysing the cost as Θ(height)\Theta(\text{height}) or Θ(∑cu)\Theta(\sum c_u) without the +1+1.

Check: the algorithm run in Python on this tree gives the table above, 13 calls and ∑cu=12=n−1\sum c_u = 12 = n - 1.

Exercise 3 (points 4)

Let P=[7,15,4,10,2,9,13,6,11]P = [7, 15, 4, 10, 2, 9, 13, 6, 11] be an array of 9 keys (indices from 0).

(a) Build a min-heap from PP 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 j=3,2,1,0j = 3, 2, 1, 0: [7,15,4,6,2,9,13,10,11][7,15,4,6,2,9,13,10,11]; [7,15,4,6,2,9,13,10,11][7,15,4,6,2,9,13,10,11]; [7,2,4,6,15,9,13,10,11][7,2,4,6,15,9,13,10,11]; [2,6,4,7,15,9,13,10,11][2,6,4,7,15,9,13,10,11]. Final heap:

           2
        /     \
       6       4
      / \     / \
     7  15   9  13
    / \
   10 11

(b) After phase A: [15,11,13,10,2,9,4,6,7][15,11,13,10,2,9,4,6,7]. Phase B: [13,11,9,10,2,7,4,6∣15][13,11,9,10,2,7,4,6 \mid 15]; [11,10,9,6,2,7,4∣13,15][11,10,9,6,2,7,4 \mid 13,15]; [10,6,9,4,2,7∣11,13,15][10,6,9,4,2,7 \mid 11,13,15].

(c) Bottom-up: ⌊9/2⌋=4\lfloor 9/2 \rfloor = 4 down-heap bubblings, total Θ(n)\Theta(n). Top-down: n−1=8n - 1 = 8 up-heap bubblings, total Θ(nlog⁡n)\Theta(n \log n).

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 n=9n = 9 the loop runs for jj from ⌊(n−2)/2⌋=3\lfloor (n-2)/2 \rfloor = 3 down to 00; the children of P[j]P[j] are P[2j+1]P[2j+1] and P[2j+2]P[2j+2], and at each step the entry goes down by swapping with its smaller child while it is larger.

jj what happens array after the iteration
3 P[3]=10P[3] = 10, children 6 and 11: swap with 6 [7,15,4,6,2,9,13,10,11][7,15,4,6,2,9,13,10,11]
2 P[2]=4P[2] = 4, children 9 and 13: 4≤94 \le 9, no swap same
1 P[1]=15P[1] = 15, children 6 and 2: swap with 2; now at index 4, a leaf [7,2,4,6,15,9,13,10,11][7,2,4,6,15,9,13,10,11]
0 P[0]=7P[0] = 7, children 2 and 4: swap with 2; at index 1, children 6 and 15: swap with 6; at index 3, children 10 and 11: 7≤107 \le 10, stop [2,6,4,7,15,9,13,10,11][2,6,4,7,15,9,13,10,11]

Total 4 swaps. The final tree is the one in the result: every parent is ≤\le its children (2≤6,42 \le 6,4; 6≤7,156 \le 7,15; 4≤9,134 \le 9,13; 7≤10,117 \le 10,11).

(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 S[2i+1]S[2i+1], S[2i+2]S[2i+2]. Phase A, j=3,2,1,0j = 3, 2, 1, 0, swapping with the larger child while smaller:

  • j=3j = 3: 1010 with children 6, 11: swap with 11, giving [7,15,4,11,2,9,13,6,10][7,15,4,11,2,9,13,6,10];
  • j=2j = 2: 44 with children 9, 13: swap with 13, giving [7,15,13,11,2,9,4,6,10][7,15,13,11,2,9,4,6,10];
  • j=1j = 1: 1515 with children 11, 2: no swap;
  • j=0j = 0: 77 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 [15,11,13,10,2,9,4,6,7][15,11,13,10,2,9,4,6,7] (3 swaps).

Phase B, iteration jj: swap S[0]S[0] with S[n−j]S[n-j] and restore the max-heap on S[0..n−j−1]S[0..n-j-1] (down-heap bounded by last):

  • j=1j = 1: swap S[0]=15S[0] = 15 with S[8]=7S[8] = 7: [7,11,13,10,2,9,4,6∣15][7,11,13,10,2,9,4,6 \mid 15]. Down-heap: 7 with 13 (children 11, 13), then at index 2 with 9 (children 9, 4). Result [13,11,9,10,2,7,4,6∣15][13,11,9,10,2,7,4,6 \mid 15].
  • j=2j = 2: swap S[0]=13S[0] = 13 with S[7]=6S[7] = 6: [6,11,9,10,2,7,4∣13,15][6,11,9,10,2,7,4 \mid 13,15]. Down-heap: 6 with 11, then at index 1 with 10 (children 10, 2). Result [11,10,9,6,2,7,4∣13,15][11,10,9,6,2,7,4 \mid 13,15].
  • j=3j = 3: swap S[0]=11S[0] = 11 with S[6]=4S[6] = 4: [4,10,9,6,2,7∣11,13,15][4,10,9,6,2,7 \mid 11,13,15]. Down-heap: 4 with 10, then at index 1 with 6 (children 6, 2). Result [10,6,9,4,2,7∣11,13,15][10,6,9,4,2,7 \mid 11,13,15].

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, [2,4,6,7,9,10,11,13,15][2,4,6,7,9,10,11,13,15].

(c) The bottom-up construction does one down-heap bubbling for each internal node, ⌊n/2⌋=4\lfloor n/2 \rfloor = 4 in this case. The top-down construction does n−1=8n - 1 = 8 up-heap bubblings, one per inserted key from the second. Asymptotically, bottom-up costs Θ(n)\Theta(n) because most nodes are near the leaves and cheap (∑i2i(h−i)<3n\sum_i 2^i (h - i) < 3n), while top-down costs Θ(nlog⁡n)\Theta(n \log n) 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 ⌊(n−2)/2⌋\lfloor (n-2)/2 \rfloor; 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 S[0..n−1]S[0..n-1] be an array of n≥0n \ge 0 integers. Design an algorithm Separate(S) that rearranges SS 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 O(1)O(1) extra space. For example [5,−3,8,−1,0,−7,2,−4,6][5,-3,8,-1,0,-7,2,-4,6] may become [−4,−3,−7,−1,0,8,2,5,6][-4,-3,-7,-1,0,8,2,5,6].

(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 [−4,−3,−7,−1,0,8,2,5,6][-4,-3,-7,-1,0,8,2,5,6] after 7 iterations and 2 swaps.

(b) Invariant: all entries of S[0..i−1]S[0..i-1] are negative, all entries of S[j+1..n−1]S[j+1..n-1] are non-negative, and S[i..j]S[i..j] contains the not yet examined entries.

(c) Initialisation: both parts are empty. Maintenance by cases. Termination: j−ij - i decreases at each iteration; at the end i=j+1i = j + 1.

(d) Θ(n)\Theta(n) on every instance; at most ⌊n/2⌋\lfloor n/2 \rfloor 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 S

Trace on S=[5,−3,8,−1,0,−7,2,−4,6]S = [5,-3,8,-1,0,-7,2,-4,6] (state at the end of each iteration, with the new ii, jj):

iteration action SS ii jj
start [5,−3,8,−1,0,−7,2,−4,6][5,-3,8,-1,0,-7,2,-4,6] 0 8
1 S[0]=5≥0S[0]=5 \ge 0, S[8]=6≥0S[8]=6 \ge 0: jj decreases same 0 7
2 S[0]=5≥0S[0]=5 \ge 0, S[7]=−4<0S[7]=-4 < 0: swap [−4,−3,8,−1,0,−7,2,5,6][-4,-3,8,-1,0,-7,2,5,6] 1 6
3 S[1]=−3<0S[1]=-3 < 0: ii increases same 2 6
4 S[2]=8≥0S[2]=8 \ge 0, S[6]=2≥0S[6]=2 \ge 0: jj decreases same 2 5
5 S[2]=8S[2]=8, S[5]=−7S[5]=-7: swap [−4,−3,−7,−1,0,8,2,5,6][-4,-3,-7,-1,0,8,2,5,6] 3 4
6 S[3]=−1<0S[3]=-1 < 0: ii increases same 4 4
7 S[4]=0≥0S[4]=0 \ge 0 and S[4]≥0S[4] \ge 0: jj decreases same 4 3

At the end i=4>j=3i = 4 > j = 3 and the result is the array of the statement.

(b) The invariant describes the state at the end of a generic iteration, with Inv\text{Inv} being the conjunction of

  1. every S[x]S[x] with 0≤x<i0 \le x < i is negative;
  2. every S[x]S[x] with j<x≤n−1j < x \le n-1 is non-negative;
  3. i≤j+1i \le j + 1, and S[i..j]S[i..j] holds the entries not yet examined (the entries of SS are always a permutation of the original ones).

(c) 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.

  • Initialisation (i=0i = 0, j=n−1j = n-1): the zones S[0..−1]S[0..-1] and S[n..n−1]S[n..n-1] are empty, so properties 1 and 2 hold by vacuity; i=0≤n=j+1i = 0 \le n = j + 1.

  • Maintenance. Assume Inv\text{Inv} holds at the start of an iteration with i≤ji \le j.

    • S[i]<0S[i] < 0: increasing ii extends the negative zone by a correct entry; 2 is untouched; i+1≤j+1i + 1 \le j + 1.
    • S[i]≥0S[i] \ge 0 and S[j]≥0S[j] \ge 0: decreasing jj extends the non-negative zone by a correct entry.
    • S[i]≥0S[i] \ge 0 and S[j]<0S[j] < 0: after the swap S[i]<0S[i] < 0 and S[j]≥0S[j] \ge 0, so both zones extend by one correct entry (i+1i + 1, j−1j - 1). If i=ji = j the case cannot occur, because S[i]≥0S[i] \ge 0 and S[j]<0S[j] < 0 would be contradictory; hence i≤j−1i \le j - 1 and the new values satisfy i+1≤(j−1)+1i + 1 \le (j - 1) + 1.

    In every case the invariant holds at the end of the iteration.

  • Termination. The size j−i+1j - i + 1 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 ≥1\ge 1, so it stops after a finite number of iterations with j−i+1≤0j - i + 1 \le 0. Together with i≤j+1i \le j + 1 this gives i=j+1i = j + 1.

  • Conclusion. At the end the unknown zone is empty: S[0..i−1]S[0..i-1] is all negative and S[i..n−1]=S[j+1..n−1]S[i..n-1] = S[j+1..n-1] is all non-negative: SendS_{end} holds.

(d) Each iteration costs Θ(1)\Theta(1) and removes 1 or 2 entries from the unknown zone, which initially has nn entries, so the number of iterations is between ⌈n/2⌉\lceil n/2 \rceil and nn: the cost is Θ(n)\Theta(n) 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 min⁡{#neg,#non-neg}≤⌊n/2⌋\min\{\#\text{neg}, \#\text{non-neg}\} \le \lfloor n/2 \rfloor. Extra space: two indices and one temporary variable, O(1)O(1).

Typical mistakes. An invariant that describes iteration ii instead of the state after it; forgetting the case S[i]≥0S[i] \ge 0 and S[j]≥0S[j] \ge 0 (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 n=1n = 1 the loop would not run, leaving the entry unchecked); forgetting to update jj 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 i=j+1i = j + 1, use between ⌈n/2⌉\lceil n/2 \rceil iterations and nn, and never exceed min⁡{#neg,#non-neg}\min\{\#\text{neg}, \#\text{non-neg}\} swaps.

Exercise 5 (points 6)

Let X0,X1,…,Xk−1X_0, X_1, \dots, X_{k-1} be k≥1k \ge 1 non-empty arrays of integers, each sorted in non-decreasing order, containing nn integers in total. Design an algorithm KMerge that returns an array R[0..n−1]R[0..n-1] with all the integers of the kk arrays in non-decreasing order, in time O(nlog⁡k)O(n \log k), using a priority queue implemented with a heap (methods insert(key, value), removeMin(), isEmpty()).

(a) Explain the idea and write the pseudocode.

(b) On X0=[3,8,12]X_0 = [3, 8, 12], X1=[1,9]X_1 = [1, 9], X2=[4,5,6,15]X_2 = [4, 5, 6, 15], X3=[2,7]X_3 = [2, 7] 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 RR.

(c) Justify the complexity O(nlog⁡k)O(n \log k). 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 RR, insert the next element of the same array (code in the solution).

(b) After the initial insertions: [1,2,4,3][1,2,4,3]. After iteration 1 (output 1): [2,3,4,9][2,3,4,9]; iteration 2 (output 2): [3,7,4,9][3,7,4,9]; iteration 3 (output 3): [4,7,9,8][4,7,9,8]. Final output R=[1,2,3,4,5,6,7,8,9,12,15]R = [1,2,3,4,5,6,7,8,9,12,15].

(c) nn insertions and nn removals on a heap with at most kk entries, each O(log⁡k)O(\log k): O(nlog⁡k)O(n \log k). One-by-one merging costs Θ(nk)\Theta(nk) 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 kk first elements. After outputting an element of XaX_a, the new candidate from XaX_a 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 (a,p)(a, p) = 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 R

Correctness (invariant at the end of an iteration). (1) R[0..t−1]R[0..t-1] contains the tt smallest elements of the union, sorted. (2) PP contains exactly one entry for each array that is not exhausted: its smallest element not yet in RR. Initially t=0t = 0 and PP 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 ≥\ge the candidate of its array, which is ≥\ge the removed minimum: it is the smallest of all the remaining elements and goes next in RR. Inserting the successor from the same array restores (2). When PP is empty, all arrays are exhausted and t=nt = n. (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 P[i]P[i] at 2i+12i+1 and 2i+22i+2).

  • Initial insertions of 3,1,4,23, 1, 4, 2: [3][3]; insert 1, it bubbles above 3: [1,3][1,3]; insert 4: [1,3,4][1,3,4]; insert 2, it bubbles above 3: [1,2,4,3][1,2,4,3].
  • Iteration 1: removeMin() returns 1 (from X1X_1, position 0). The last key 3 goes to the root, [3,2,4][3,2,4], and bubbles down with its smaller child 2: [2,3,4][2,3,4]. Output R=[1]R = [1]. Insert the next element of X1X_1, which is 9: [2,3,4,9][2,3,4,9].
  • Iteration 2: removeMin() returns 2 (from X3X_3). The last key 9 goes to the root, [9,3,4][9,3,4], down with 3: [3,9,4][3,9,4]. R=[1,2]R = [1,2]. Insert 7 (next of X3X_3), it bubbles above 9: [3,7,4,9][3,7,4,9].
  • Iteration 3: removeMin() returns 3 (from X0X_0). The last key 9 goes to the root, [9,7,4][9,7,4], down with 4: [4,7,9][4,7,9]. R=[1,2,3]R = [1,2,3]. Insert 8 (next of X0X_0): [4,7,9,8][4,7,9,8].

The remaining iterations give R=[1,2,3,4,5,6,7,8,9,12,15]R = [1,2,3,4,5,6,7,8,9,12,15]: 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 kk entries, so its height is ≤log⁡2k\le \log_2 k and each insert and removeMin costs O(log⁡k)O(\log k). Each element is inserted exactly once and removed exactly once: nn insertions and nn removals, and the loop makes nn iterations with Θ(1)\Theta(1) other work. Total O(nlog⁡k)O(n \log k) (more precisely O(n(1+log⁡k))O(n(1 + \log k)), so O(n)O(n) for k=1k = 1). The arrays are non-empty, hence k≤nk \le n, and the first kk insertions are part of the nn. Extra space: Θ(k)\Theta(k) for the heap, plus the output RR.

Merging the arrays one after the other (first with second, the result with the third, ...) copies the accumulated result each time: with arrays of n/kn/k elements the ii-th merge handles about in/ki n / k elements, so the total is ∑i=1kin/k=Θ(nk)\sum_{i=1}^{k} i n/k = \Theta(nk), much more than nlog⁡kn \log k when kk grows. The heap pays only log⁡k\log k per element, because it does not rescan the elements already merged. A third approach, concatenating everything and sorting, costs Θ(nlog⁡n)\Theta(n \log n).

Typical mistakes. Inserting all nn elements first (heap of size nn, cost Θ(nlog⁡n)\Theta(n \log n) and extra space Θ(n)\Theta(n)); 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 p+1<nap + 1 < n_a 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 kk from 1 to 12. Counting heap comparisons, the ratio between the operations and nlog⁡2kn \log_2 k stays between 1.0 and 1.3 for k=2,4,16,64,256k = 2, 4, 16, 64, 256 and nn 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 kk highest scores. The cut is the kk-th highest score among all the scores received so far (equal scores count separately: in [7,7,5][7,7,5] the 2nd highest is 7). Implement the class below.

java
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:

  • 1≤k≤1041 \le k \le 10^4;
  • 0≤initial.length≤1040 \le \text{initial.length} \le 10^4, with initial.length+1≥k\text{initial.length} + 1 \ge k (so at every call of add there are at least kk scores);
  • −104≤score≤104-10^4 \le \text{score} \le 10^4, for the initial scores and for the scores passed to add;
  • at most 10410^4 calls to add.

Required complexity: the constructor in O(mlog⁡k)O(m \log k) (mm = initial.length), each call of add in O(log⁡k)O(\log k), extra space O(k)O(k).

Examples:

  1. k = 3, initial = [4, 5, 8, 2]; calls add(3), add(5), add(10), add(9), add(4) return 4, 5, 5, 8, 8.
  2. k = 1, initial = []; calls add(-3), add(-1), add(-5) return -3, -1, -1.
  3. k = 2, initial = [7, 7, 7]; calls add(7), add(1) return 7, 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 kk highest scores; the cut is its root.

Show the full solution

Idea. Sorting all the scores at every call costs Θ(mlog⁡m)\Theta(m \log m) per call: too slow. Only the kk 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 kk gives exactly that: its root min() is the smallest of the kk highest scores, i.e. the kk-th highest. This is the top-kk 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 kk entries, insert the score.
  • Otherwise, if the score is strictly larger than the root, it beats the current kk-th: removeMin() then insert. If it is not larger, it is not among the kk highest and is ignored (a score equal to the root changes nothing for the kk-th highest value).

Each score costs O(log⁡k)O(\log k) (the heap never exceeds kk entries), so the constructor costs O(mlog⁡k)O(m \log k), add costs O(log⁡k)O(\log k) and the space is O(k)O(k). 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().

java
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 (k=3k = 3): after the constructor the heap holds the three highest of 4,5,8,24,5,8,2, i.e. {4,5,8}\{4,5,8\} (the 2 was ignored when the heap was full and 2 is below the root 4). add(3): 3<43 < 4, ignored, root 4, answer 4. add(5): 5>45 > 4, the 4 leaves: {5,5,8}\{5,5,8\}, answer 5. add(10): 10>510 > 5: {5,8,10}\{5,8,10\}, answer 5. add(9): {8,9,10}\{8,9,10\}, answer 8. add(4): 4<84 < 8, ignored, answer 8. Output 4 5 5 8 8, as expected. Example 2: with k=1k = 1 the heap holds the maximum: −3-3, then −1-1 replaces it, then −5-5 is ignored: -3 -1 -1. Example 3: heap {7,7}\{7,7\}, add(7): 7>77 > 7 is false, ignored, answer 7; add(1) ignored, answer 7: 7 7.

Edge cases. k=1k = 1 (the heap is the running maximum); empty initial (the first add has at least kk scores only if k=1k = 1, guaranteed by the constraint m+1≥km + 1 \ge k); negative and repeated scores (the comparison s > top.peek() is strict: a repeated score is already represented, nothing changes); kk 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 kk-th); letting the heap grow beyond kk (time and space O(m)O(m) 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 kk from 1 to 6, up to 7 initial and 8 added scores in [−10,10][-10, 10], 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 kk-th largest. A run with the maximum sizes (k=104k = 10^4, 10410^4 initial scores, 10410^4 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 T(n)=T(n−1)+nT(n) = T(n-1) + n with T(1)=1T(1) = 1 and induction proof of n(n+1)/2n(n+1)/2 with base and step (1.5); (c) Θ(n2)\Theta(n^2) for every instance and nn activation records (0.5) cost Θ(1)\Theta(1) 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 d+1d+1, base case at leaves and initial call (2); (c) one call per node, cost Θ(cu+1)\Theta(c_u + 1) and ∑cu=n−1\sum c_u = n - 1, so Θ(n)\Theta(n) (1) forgetting that a node is its own descendant; dd not incremented; cost stated without +1+1 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 Θ(n)\Theta(n) versus Θ(nlog⁡n)\Theta(n \log n) (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) Θ(n)\Theta(n) and at most ⌊n/2⌋\lfloor n/2 \rfloor swaps (0.5) invariant on iteration ii instead of the state after it; i < j; missing case with two non-negative ends
5 6 (a) idea, correct pseudocode with (a,p)(a, p) in the value and the test p+1<nap + 1 < n_a (3); (b) correct heap states and output (1); (c) heap size ≤k\le k, nn insertions and removals, O(nlog⁡k)O(n \log k), and the comparison with one-by-one merging (2) heap of size nn; losing the successor; analysis Θ(nlog⁡n)\Theta(n \log n) without the size of the heap
6 10 (proposal) correct class with a min-heap of size kk (6); the three examples give the expected outputs (2); complexity O(log⁡k)O(\log k) per call and O(k)O(k) space justified (2) max-heap; heap larger than kk; sorting at each call