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

Data Structures and Algorithms - Mock Exam 1

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 written-exam examples of the equivalent course in Italian (Dati e Algoritmi, UniPD): the same two parts and the same points. Part 1 (Exercises 1-3: 3 + 4 + 4 = 11 points) is made of short questions on analysis and theory. Part 2 (Exercises 4-5: 5 + 6 = 11 points) asks to run an algorithm on a data structure and to design an algorithm in pseudocode with its analysis. The official sheets do not give the duration: 150 minutes for Parts 1 and 2 is our proposal. No material is allowed (books, notes, phone, computer).

The real exam also has a programming part. Part 3 (Exercise 6) is our proposal, in the style of programming-contest problems: 8 points and 60 extra minutes are our choice, not an official rule. The problem is inspired by a classic one but rewritten with its own text and data. In total the mock exam is worth 30 points.

Every result was checked with a program: exact counts of the loops, an exhaustive check of the induction claim on all binary trees up to 10 nodes, all traversals and the rebuilding of the tree, every heap operation, the recursive algorithm against a brute-force solution on random trees, and the Java code (compiled and run with JDK 21).

Exercise 1 (points 3)

(a) Count how many times the statement s <- s + 1 is executed by each of the two fragments below, as an exact function of nn, and give its order of growth with Θ\Theta.

Fragment A                          Fragment B
s <- 0                              s <- 0
for i <- 1 to n do                  i <- n
    for j <- 1 to 2*i do            while (i >= 1) do
        s <- s + 1                      for j <- 1 to n do
                                            s <- s + 1
                                        i <- floor(i/2)

(b) Using only the definition of big-oh:

  1. prove that 6n2+5n+4∈O(n2)6n^2 + 5n + 4 \in O(n^2), giving explicit constants cc and n0n_0;
  2. prove that n2∉O(n)n^2 \notin O(n).
Show the result

(a) Fragment A: n(n+1)n(n+1) executions, so Θ(n2)\Theta(n^2). Fragment B: n (⌊log⁡2n⌋+1)n\,(\lfloor \log_2 n \rfloor + 1) executions, so Θ(nlog⁡n)\Theta(n \log n).

(b) 1. For example c=15c = 15, n0=1n_0 = 1: 6n2+5n+4≤15n26n^2 + 5n + 4 \le 15 n^2 for all n≥1n \ge 1. 2. Whatever cc and n0n_0 are chosen, n2≤c nn^2 \le c\,n fails for n=max⁡{n0,⌈c⌉+1}n = \max\{n_0, \lceil c \rceil + 1\}.

Show the full solution

(a) Fragment A. For a fixed ii the inner loop runs 2i2i times, and the statement costs one operation. Total (Gauss' formula, see 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 →):

∑i=1n2i=2⋅n(n+1)2=n(n+1).\sum_{i=1}^{n} 2i = 2 \cdot \frac{n(n+1)}{2} = n(n+1).

Since n2≤n(n+1)≤2n2n^2 \le n(n+1) \le 2n^2 for n≥1n \ge 1, the count is Θ(n2)\Theta(n^2). The bound holds for every nn, because the loops do not depend on the data.

Fragment B. The inner loop always executes nn times. The outer loop starts with i=ni = n and halves ii (integer part) until it becomes 00: the values are n,⌊n/2⌋,⌊n/4⌋,…,1n, \lfloor n/2 \rfloor, \lfloor n/4 \rfloor, \dots, 1. The value ⌊n/2k⌋\lfloor n/2^k \rfloor is at least 11 exactly when 2k≤n2^k \le n, that is k≤⌊log⁡2n⌋k \le \lfloor \log_2 n \rfloor. So there are ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 iterations and the count is

n (⌊log⁡2n⌋+1).n\,(\lfloor \log_2 n \rfloor + 1).

For n≥2n \ge 2 we have log⁡2n−1<⌊log⁡2n⌋≤log⁡2n\log_2 n - 1 < \lfloor \log_2 n \rfloor \le \log_2 n, so nlog⁡2n≤n (⌊log⁡2n⌋+1)≤n (log⁡2n+1)≤2nlog⁡2nn \log_2 n \le n\,(\lfloor \log_2 n \rfloor + 1) \le n\,(\log_2 n + 1) \le 2n\log_2 n (the last step uses log⁡2n≥1\log_2 n \ge 1). Hence Θ(nlog⁡n)\Theta(n \log n).

Check: n=4n = 4 gives 4⋅3=124 \cdot 3 = 12 for B and 4⋅5=204 \cdot 5 = 20 for A; n=1000n = 1000 gives 10 00010\,000 for B and 1 001 0001\,001\,000 for A (both confirmed by running the loops).

Typical mistakes: counting ∑i=1ni\sum_{i=1}^{n} i for A (forgetting the factor 2, which does not change Θ\Theta but changes the exact count); writing log⁡2n\log_2 n iterations for B instead of ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 (the iteration with i=1i = 1 counts); thinking B is Θ(n2)\Theta(n^2) because it has two nested loops.

(b) 1. Recall the definition: f(n)∈O(g(n))f(n) \in O(g(n)) if there are constants c>0c > 0 and n0≥1n_0 \ge 1 such that f(n)≤c g(n)f(n) \le c\,g(n) for all n≥n0n \ge n_0. Take g(n)=n2g(n) = n^2 (the dominant term) and write each lower-order term as a multiple of n2n^2. For n≥1n \ge 1 we have n≤n2n \le n^2 and 1≤n21 \le n^2, so

6n2+5n+4≤6n2+5n2+4n2=15 n2.6n^2 + 5n + 4 \le 6n^2 + 5n^2 + 4n^2 = 15\,n^2 .

The inequality holds for all n≥1n \ge 1, so c=15c = 15 and n0=1n_0 = 1 work. (Other choices are also correct, for instance c=7c = 7 and n0=6n_0 = 6, because 6n2+5n+4≤7n26n^2 + 5n + 4 \le 7n^2 means 5n+4≤n25n + 4 \le n^2, which holds for n≥6n \ge 6; the definition only asks that some pair exists.)

(b) 2. Proof by contradiction (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 →). Suppose n2∈O(n)n^2 \in O(n): there are c>0c > 0 and n0≥1n_0 \ge 1 with n2≤c nn^2 \le c\,n for every n≥n0n \ge n_0. Dividing by n>0n > 0 gives n≤cn \le c for every n≥n0n \ge n_0. This is false for the integer n=max⁡{n0,⌈c⌉+1}n = \max\{n_0, \lceil c \rceil + 1\}, which is ≥n0\ge n_0 and larger than cc. Contradiction, so n2∉O(n)n^2 \notin O(n).

Typical mistakes: choosing cc or n0n_0 that depend on nn; proving the inequality for some values of nn only; for part 2, trying a few numbers instead of showing that no constants work.

Exercise 2 (points 4)

Let TT be a non-empty binary tree: every node has at most two children, and a node with only one child may have it as left or as right child. Let nn be the number of nodes, n0n_0 the number of leaves, n1n_1 the number of nodes with exactly one child and n2n_2 the number of nodes with exactly two children.

(a) Prove by induction on nn that n0=n2+1n_0 = n_2 + 1.

(b) Deduce that in a proper binary tree with nn nodes and mm leaves, m=(n−m)+1m = (n - m) + 1.

(c) A binary tree has 23 nodes and 11 leaves. How many nodes have exactly one child? Can the tree be proper?

(d) Can a proper binary tree have 14 nodes and 7 leaves?

Show the result

(a) n0=n2+1n_0 = n_2 + 1 holds for every non-empty binary tree (induction on nn, three cases on the root: base case n=1n = 1, root with one child, root with two children).

(b) m=n0=n2+1=(n−m)+1m = n_0 = n_2 + 1 = (n - m) + 1.

(c) n1=2n_1 = 2; the tree is not proper.

(d) No.

Show the full solution

(a) The claim Q(n)Q(n): every binary tree with nn nodes satisfies n0=n2+1n_0 = n_2 + 1. We use the induction scheme of 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 →: one base case (the smallest tree, n=1n = 1) and a step that assumes the claim for all sizes up to nn.

  • Base case n=1n = 1. The tree is a single node: it is a leaf, so n0=1n_0 = 1, and there are no nodes with two children, so n2=0n_2 = 0. Indeed 1=0+11 = 0 + 1.
  • Inductive step. Fix n≥1n \ge 1 and assume Q(m)Q(m) for all 1≤m≤n1 \le m \le n. Take a tree TT with n+1≥2n + 1 \ge 2 nodes. Its root rr is not a leaf (a leaf alone would give n+1=1n + 1 = 1), so rr has one or two children. Look at what rr contributes to the three counts: a node with one child contributes to n1n_1, a node with two children contributes to n2n_2.
    • Case 1: rr has one child. Removing rr leaves a tree T′T' with nn nodes (the subtree of the child). The root adds nothing to n0n_0 or to n2n_2, and every other node keeps its number of children, so n0(T)=n0(T′)n_0(T) = n_0(T') and n2(T)=n2(T′)n_2(T) = n_2(T'). By the hypothesis on T′T': n0(T)=n2(T′)+1=n2(T)+1n_0(T) = n_2(T') + 1 = n_2(T) + 1.
    • Case 2: rr has two children. The two subtrees T1,T2T_1, T_2 are non-empty binary trees with n1′,n2′≥1n_1', n_2' \ge 1 nodes and n1′+n2′=nn_1' + n_2' = n, so both have at most nn nodes and the hypothesis applies to both. The leaves of TT are the leaves of T1T_1 and of T2T_2: n0(T)=n0(T1)+n0(T2)n_0(T) = n_0(T_1) + n_0(T_2). The nodes with two children are those of T1T_1, those of T2T_2, and the root: n2(T)=n2(T1)+n2(T2)+1n_2(T) = n_2(T_1) + n_2(T_2) + 1. Then n0(T)=(n2(T1)+1)+(n2(T2)+1)=(n2(T1)+n2(T2)+1)+1=n2(T)+1.n_0(T) = (n_2(T_1) + 1) + (n_2(T_2) + 1) = (n_2(T_1) + n_2(T_2) + 1) + 1 = n_2(T) + 1.

In both cases Q(n+1)Q(n + 1) holds, which proves the claim for every n≥1n \ge 1. (Strong induction is needed in Case 2, because the two subtrees have different sizes.) Computer check: the equality holds for all 23 71323\,713 binary tree shapes with up to 10 nodes.

(b) A proper binary tree has no node with exactly one child: n1=0n_1 = 0. So the nodes are leaves or nodes with two children, n=n0+n2n = n_0 + n_2, hence n2=n−n0n_2 = n - n_0. Put this into (a), with m=n0m = n_0: m=n2+1=(n−m)+1.m = n_2 + 1 = (n - m) + 1 . This is Property 1 of 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 →, now proved in one line from a more general statement.

(c) From n=n0+n1+n2n = n_0 + n_1 + n_2 with n=23n = 23, n0=11n_0 = 11 and n2=n0−1=10n_2 = n_0 - 1 = 10 (by (a)): n1=23−11−10=2.n_1 = 23 - 11 - 10 = 2 . Since n1≠0n_1 \ne 0, the tree is not proper.

(d) In a proper tree n1=0n_1 = 0, so n=n0+n2=2n0−1n = n_0 + n_2 = 2n_0 - 1. With n0=7n_0 = 7 leaves we get n=13n = 13, not 1414. So the answer is no (equivalently: a proper binary tree always has an odd number of nodes).

Typical mistakes: checking the claim on a few trees instead of proving it for all of them; forgetting the case of a root with one child; using n1n_1 and n2n_2 for the sizes of the subtrees and for the counts at the same time; assuming the tree is proper in (a), which would make the case of one child disappear.

Exercise 3 (points 4)

(a) Consider the binary tree TT below (the letters are only names of the nodes). Write the sequences of nodes visited by the preorder, the inorder and the postorder traversals of TT, always visiting the left child before the right child.

            A
          /   \
        B       C
       / \     /
      D   E   F
       \     / \
        G   H   I

(b) A binary tree T′T' with 8 nodes has preorder S K N Q Z V R T and inorder N K Q Z S R T V. Draw T′T' and write its postorder.

(c) Are the preorder and the postorder of a binary tree enough to rebuild it? Answer with a small example.

Show the result

(a) Preorder: A B D G E C F H I. Inorder: D G B E A H F I C. Postorder: G D E B H I F C A.

(b) Root S; left subtree: K with left child N and right child Q, and Q has the right child Z; right subtree: V with left child R, and R has the right child T. Postorder: N Z Q K T R V S.

(c) No. The trees "A with left child B" and "A with right child B" have the same preorder A B and the same postorder B A, but different inorder sequences.

Show the full solution

(a) Use the three patterns of 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 → and Binary Tree Traversals and Expression TreesInorder visits the left subtree, the node, then the right subtree; on the parse tree of an arithmetic expression postorder evaluates the expression and inorder rebuilds the fully parenthesized infix form, both in linear time.Binary Tree Traversals and Expression Trees →: preorder = node, left subtree, right subtree; inorder = left subtree, node, right subtree; postorder = left subtree, right subtree, node. A missing child is simply skipped.

  • Preorder: A, then the subtree of B (B, then D with its right child G, then E), then the subtree of C (C, then F with H and I): A B D G E C F H I.
  • Inorder: first the whole left subtree of A. In the subtree of B: D has no left child, so D, then its right child G; then B; then E. Then A. Then the subtree of C: C has only a left child, so first the subtree of F (H, F, I) and then C: D G B E A H F I C.
  • Postorder: subtree of B: for D first its subtree (G) then D; then E; then B. Subtree of C: H, I, F, then C. Last A: G D E B H I F C A.

Check: the three sequences contain all 9 letters exactly once, the first of the preorder and the last of the postorder are the root A, and in the inorder the letters before A (D G B E) are exactly the left subtree of A. All three were also produced by a program.

(b) Two facts: the first node of the preorder of a subtree is its root; in the inorder the nodes of the left subtree come before the root and those of the right subtree after it.

  1. Preorder S K N Q Z V R T: the root is S. In the inorder N K Q Z S R T V there are 4 nodes before S (N K Q Z: left subtree) and 3 after (R T V: right subtree).
  2. The preorder after S splits accordingly: the next 4 letters K N Q Z are the preorder of the left subtree, the last 3 letters V R T are the preorder of the right subtree.
  3. Left subtree: preorder K N Q Z, inorder N K Q Z. Root K; before K in the inorder there is N (left subtree), after K there are Q Z (right subtree). Preorder of the left part: N. Preorder of the right part: Q Z, inorder Q Z: root Q, nothing before it, so no left child, and Z is the right child of Q.
  4. Right subtree: preorder V R T, inorder R T V. Root V; everything (R T) is before V, so V has only a left child, the subtree R T. Preorder R T, inorder R T: root R, T after R in the inorder, so T is the right child of R.
            S
          /   \
        K       V
       / \     /
      N   Q   R
           \   \
            Z   T

Postorder (left, right, node): left subtree of S gives N, then Z Q (Q's subtree), then K: N Z Q K; right subtree gives T R then V: T R V; then S. N Z Q K T R V S.

The tree is unique: a program enumerated every binary tree with that preorder (1430 shapes) and only this one has that inorder. Two traversals with distinct labels, one of them the inorder, determine the tree.

(c) No, when nodes with one child exist. The two trees below are different (B is the left child in the first one, the right child in the second one) but have preorder A B and postorder B A:

   A        A
  /          \
 B            B

Only the inorder tells them apart: B A for the first tree and A B for the second. For the tree T′T' of (b), the pair preorder and postorder is compatible with 8 different binary trees. (With a proper binary tree, preorder and postorder do determine the tree, but this is not needed here.)

Typical mistakes: visiting the right child before the left one; in the inorder of a node with only a left child, writing the node before the child; splitting the preorder using the wrong sizes (the size of the left part comes from the inorder, not from the preorder); trying to rebuild a tree from preorder and postorder only.

Exercise 4 (points 5)

A min-heap is stored in an array PP with level numbering (the root is in P[0]P[0], the children of P[i]P[i] are in P[2i+1]P[2i+1] and P[2i+2]P[2i+2]). It is initially empty. Only the keys are shown.

(a) Perform in order insert(14), insert(9), insert(21), insert(5), insert(17), insert(3), insert(11), insert(8). After each insertion write the content of the array and the number of swaps made by the up-heap bubbling.

(b) Draw the heap after the eight insertions as a tree.

(c) On the heap of (b) perform in order removeMin(), removeMin(), insert(4), removeMin(). For each operation write the returned key (if any), the number of swaps and the array after the operation.

(d) A min-heap contains 1000 entries. What is the maximum number of swaps that a single insert can make? And a single removeMin? Justify the answers and say whether each maximum is actually reached.

Show the result

(a)

operation array swaps
insert(14) [14] 0
insert(9) [9, 14] 1
insert(21) [9, 14, 21] 0
insert(5) [5, 9, 21, 14] 2
insert(17) [5, 9, 21, 14, 17] 0
insert(3) [3, 9, 5, 14, 17, 21] 2
insert(11) [3, 9, 5, 14, 17, 21, 11] 0
insert(8) [3, 8, 5, 9, 17, 21, 11, 14] 2

(b)

            3
         /     \
        8       5
       / \     / \
      9   17  21  11
     /
    14

(c)

operation returned array swaps
removeMin() 3 [5, 8, 11, 9, 17, 21, 14] 2
removeMin() 5 [8, 9, 11, 14, 17, 21] 2
insert(4) - [4, 9, 8, 14, 17, 21, 11] 2
removeMin() 4 [8, 9, 11, 14, 17, 21] 1

(d) At most 9 swaps for insert and at most 9 for removeMin; both maxima are reached.

Show the full solution

Recall from 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 →: insert puts the new entry in the first free cell (after Last) and swaps it with its parent, at P[⌊(i−1)/2⌋]P[\lfloor (i-1)/2 \rfloor], while the parent's key is larger. removeMin returns P[0]P[0], moves the Last entry into P[0]P[0] and swaps it with the child of smaller key while it is larger than that child. The keys are all distinct, so there are no ties.

(a) Step by step (the new key is in cell ii before bubbling):

  1. insert(14): cell 0, no parent: [14].
  2. insert(9): cell 1, parent cell 0 holds 14 > 9, swap: [9, 14]. 1 swap.
  3. insert(21): cell 2, parent 9 < 21, stop: [9, 14, 21]. 0 swaps.
  4. insert(5): cell 3, parent is cell 1 (14 > 5), swap; now 5 is in cell 1, parent cell 0 (9 > 5), swap: [5, 9, 21, 14]. 2 swaps.
  5. insert(17): cell 4, parent cell 1 (9 < 17), stop: [5, 9, 21, 14, 17]. 0 swaps.
  6. insert(3): cell 5, parent cell 2 (21 > 3), swap; cell 2, parent cell 0 (5 > 3), swap: [3, 9, 5, 14, 17, 21]. 2 swaps.
  7. insert(11): cell 6, parent cell 2 (5 < 11), stop: [3, 9, 5, 14, 17, 21, 11]. 0 swaps.
  8. insert(8): cell 7, parent cell 3 (14 > 8), swap; cell 3, parent cell 1 (9 > 8), swap; cell 1, parent cell 0 (3 < 8), stop: [3, 8, 5, 9, 17, 21, 11, 14]. 2 swaps.

(b) Cell ii is a node, with children in cells 2i+12i+1 and 2i+22i+2: cells 1, 2 under 0; cells 3, 4 under 1; cells 5, 6 under 2; cell 7 under 3. The tree is the one drawn in the result. Each parent is smaller than its children (3 < 8, 5; 8 < 9, 17; 5 < 21, 11; 9 < 14).

(c)

  1. removeMin(): returns P[0]=3P[0] = 3. The Last entry 14 (cell 7) goes into cell 0, array [14, 8, 5, 9, 17, 21, 11]. The children of cell 0 are 8 and 5: the smaller is 5 (cell 2), 14 > 5, swap. Now 14 is in cell 2, with children 21 and 11: the smaller is 11 (cell 6), 14 > 11, swap. Cell 6 is a leaf. Result [5, 8, 11, 9, 17, 21, 14], 2 swaps.
  2. removeMin(): returns 5. Last = 14 goes to cell 0: [14, 8, 11, 9, 17, 21]. Children 8 and 11, the smaller is 8 (cell 1), swap. Cell 1 has children 9 (cell 3) and 17 (cell 4): 9 is smaller than 14, swap. Cell 3 has no children (cell 7 does not exist any more). Result [8, 9, 11, 14, 17, 21], 2 swaps.
  3. insert(4): cell 6, parent cell 2 holds 11 > 4, swap; cell 2, parent cell 0 holds 8 > 4, swap. Result [4, 9, 8, 14, 17, 21, 11], 2 swaps.
  4. removeMin(): returns 4. Last = 11 goes to cell 0: [11, 9, 8, 14, 17, 21]. Children 9 and 8, the smaller is 8 (cell 2), swap. Cell 2 has the single child 21 (cell 5): 11 < 21, stop. Result [8, 9, 11, 14, 17, 21], 1 swap.

The last array is the same as after the second operation: with these data the insertion of 4 and its removal cancel out. (The array is sorted, and a sorted array is always a valid min-heap.)

(d) The cost of both operations is bounded by the height, see 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 → (Θ(log⁡n)\Theta(\log n)).

  • insert: after the insertion the heap has 1001 entries, so its height is ⌊log⁡21001⌋=9\lfloor \log_2 1001 \rfloor = 9, and the new entry starts in the last level (depth 9). Each swap moves it one level up, so at most 9 swaps. The maximum is reached when the new key is smaller than all the others: for the array [1,2,…,1000][1, 2, \dots, 1000] (sorted, hence a heap) the call insert(0) makes exactly 9 swaps.
  • removeMin: after the removal there are 999 entries, height ⌊log⁡2999⌋=9\lfloor \log_2 999 \rfloor = 9. The entry moved to the root can go down at most to the deepest level, so at most 9 swaps. It is reached for example on [1,2,…,1000][1, 2, \dots, 1000]: the Last entry 1000 goes to the root and always swaps with the smaller child, that is the left one, along cells 0, 1, 3, 7, 15, 31, 63, 127, 255, 511 (cell 511 exists because 511≤998511 \le 998). That is 9 swaps.

Both values were confirmed by running the operations on that array; on 300 random heaps with 1000 entries the number of swaps never exceeded 9.

Typical mistakes: using a non-strict test and swapping equal keys; in removeMin swapping with the larger child, or with the first child that is smaller than the moved key (the correct rule is the child of smaller key); counting cells from 1 and using 2i2i and 2i+12i+1; after the removal forgetting that the array has one entry fewer; writing the height as log⁡2n\log_2 n without the floor.

Exercise 5 (points 6)

A binary tree TT is given by the usual methods: T.left(v) and T.right(v) return the child or null if it does not exist, and T.root() returns the root (assume TT is not empty). The height of a leaf is 00 and the height of a missing child is −1-1. TT is balanced if for every node vv of TT the heights of the left and of the right subtree of vv (a missing subtree has height −1-1) differ by at most 1.

(a) Design a recursive algorithm heightBalanced(T, v) that returns, for the subtree TvT_v, whether it is balanced and its height. Write the pseudocode with input and output, the initial call that solves the problem for the whole tree, and explain why a recursive call that returns only a Boolean value would not be enough.

(b) Analyse the complexity of heightBalanced(T, T.root()) as a function of the number nn of nodes of TT. For full marks it must be O(n)O(n).

(c) Run the algorithm on the tree below and write, for each node, the pair returned by its call, in the order in which the calls end.

          P
        /   \
       Q     U
      / \   /
     R   T V
    /     /
   S     W
Show the result

(a) heightBalanced(T, v) returns the pair (b,h)(b, h): bb = "TvT_v is balanced", hh = height of vv. Initial call heightBalanced(T, T.root()), first component of the answer.

(b) Θ(n)\Theta(n) for every tree: one call per node, constant cost per call.

(c) Order of the calls: S (true, 0), R (true, 1), T (true, 0), Q (true, 2), W (true, 0), V (true, 1), U (false, 2), P (false, 3). The tree is not balanced, because of node U (left subtree of height 1, right subtree missing).

Show the full solution

(a) Idea. A node vv is "good" if the heights of its two subtrees differ by at most 1, and TvT_v is balanced if vv is good and both subtrees are balanced. The test at vv needs the heights of the two subtrees, and the height of vv itself (for its parent) is 1+max⁡1 + \max of them. So this is a postorder pattern (first the children, then the visit of vv, 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 →) in which each call returns two values: whether the subtree is balanced, and its height. This is the same lesson as the heightSum exercise in Binary Tree Traversals and Expression TreesInorder visits the left subtree, the node, then the right subtree; on the parse tree of an arithmetic expression postorder evaluates the expression and inorder rebuilds the fully parenthesized infix form, both in linear time.Binary Tree Traversals and Expression Trees →: it is useful to compute information richer than what is asked.

Algorithm heightBalanced(T, v)
Input:  binary tree T, node v in T
Output: pair (b, h): b = true iff the subtree T_v is balanced,
        h = height of v in T
hL <- -1; hR <- -1; bL <- true; bR <- true
if (T.left(v) != null) then
    (bL, hL) <- heightBalanced(T, T.left(v))
if (T.right(v) != null) then
    (bR, hR) <- heightBalanced(T, T.right(v))
h <- max{hL, hR} + 1
b <- bL AND bR AND (|hL - hR| <= 1)
return (b, h)

Initial call: (b, h) <- heightBalanced(T, T.root()). bb tells whether TT is balanced and hh is the height of TT. Base case: a leaf has no children, the two if do nothing, so it returns (true, 0) (since max⁡{−1,−1}+1=0\max\{-1, -1\} + 1 = 0 and ∣−1−(−1)∣=0|{-1} - (-1)| = 0). The pair returned by each recursive call is assigned to variables, otherwise it would be lost (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 →). The missing children are handled by the initial values −1-1 of hL and hR, so the algorithm never calls itself on null.

Why a Boolean is not enough. If the call returned only "balanced or not", the parent would know whether the two subtrees are balanced but not how tall they are, so it could not check ∣hL−hR∣≤1|h_L - h_R| \le 1. It would have to compute the two heights again with the algorithm height of 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 →, which visits the whole subtree: this costs Θ(∣Tv∣)\Theta(|T_v|) at every node and, in total, Θ(∑v∣Tv∣)=Θ(∑v(depth(v)+1))\Theta(\sum_v |T_v|) = \Theta(\sum_v (\text{depth}(v) + 1)): Θ(nlog⁡n)\Theta(n \log n) on a perfect tree and Θ(n2)\Theta(n^2) on a long path if every node is examined. Returning the height together with the Boolean avoids this.

(b) Complexity. Use the recursion tree, as for the traversals 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 →.

  • Number of calls. The initial call is on the root, and every other node receives exactly one call, from its parent (and only if it exists). So the recursion tree has exactly nn nodes, one per node of TT. The calls are made whatever the values of bb and hh: the algorithm has no early exit.
  • Cost of one call, recursive calls excluded. T.left, T.right, the comparisons, the maximum, the absolute value and the assignments take constant time, the two if at most two tests: Θ(1)\Theta(1).
  • Total. n⋅Θ(1)=Θ(n)n \cdot \Theta(1) = \Theta(n), for every tree: best and worst case coincide. In the notation of the notes, it is the postorder cost Θ(n+∑utu)\Theta(n + \sum_u t_u) with tu=Θ(1)t_u = \Theta(1). Counting the calls on random trees of 10, 100, 1000 and 5000 nodes gave exactly 10, 100, 1000 and 5000 calls.

(c) Run on the tree. Postorder, left subtree first:

  1. S is a leaf: (true, 0).
  2. R has only the left child S with hL=0h_L = 0 and hR=−1h_R = -1; ∣0−(−1)∣=1≤1|0 - (-1)| = 1 \le 1, so bb = true and h=1h = 1: (true, 1).
  3. T is a leaf: (true, 0).
  4. Q has children R (height 1) and T (height 0): difference 1, both balanced: (true, 2).
  5. W is a leaf: (true, 0).
  6. V has the left child W: hL=0h_L = 0, hR=−1h_R = -1: (true, 1).
  7. U has the left child V with height 1 and no right child: ∣1−(−1)∣=2>1|1 - (-1)| = 2 > 1, so bb = false and h=2h = 2: (false, 2).
  8. P has the left child Q with height 2 and the right child U with height 2: the heights are equal, but bRb_R = false, so bb = false and h=3h = 3: (false, 3).

The answer is "not balanced", height 3. Note that at the root the two heights are equal: only the Boolean values coming up from the subtrees reveal the problem in U.

Typical mistakes: checking only the difference of the heights at the root; using 00 instead of −1-1 for a missing child (then a node with a single child of height 1 and no other child would look balanced, although the difference is 2); forgetting to propagate bL and bR; writing the recursive calls without using the returned pair; calling height at every node and claiming O(n)O(n).

Exercise 6 (points 8)

Part 3, programming (proposed part). Rising tide. A tide gauge records the water level once per hour and stores the nn readings in an array level. For every hour ii you want to know how many hours you must wait to see a strictly higher level than at hour ii.

Write in Java the method

java
static int[] waitHours(int[] level)

that returns an array result of length nn where result[i] is the smallest d≥1d \ge 1 such that i+d≤n−1i + d \le n - 1 and level[i + d] > level[i], or 00 if no later reading is higher.

Constraints: 1≤n≤1061 \le n \le 10^6 and 0≤level[i]≤1060 \le \text{level}[i] \le 10^6. Required complexity: O(n)O(n) time and O(n)O(n) extra space. A solution that compares every reading with all the following ones takes O(n2)O(n^2) and is too slow for the largest inputs.

Examples:

input level output
[3, 5, 4, 4, 7, 2, 6] [1, 3, 2, 1, 0, 1, 0]
[9, 8, 7, 6] [0, 0, 0, 0]
[2, 2, 2, 5] [3, 2, 1, 0]

In the third example the equal readings are not higher, so hours 0, 1 and 2 all wait for the 5.

(a) Describe the idea and the data structure. (b) Write the Java code. (c) State and justify the time and the space complexity.

Show the result

Outputs of the three examples: [1, 3, 2, 1, 0, 1, 0], [0, 0, 0, 0], [3, 2, 1, 0]. Time Θ(n)\Theta(n) (each index is pushed once and popped at most once), extra space Θ(n)\Theta(n) (the result and the stack).

Show the full solution

Check of the first example. Index 0 (level 3): the next reading, 5, is higher, wait 1. Index 1 (5): 4, 4 are not higher, 7 at index 4, wait 3. Index 2 (4): the next one, 4, is not strictly higher, 7 at index 4, wait 2. Index 3 (4): 7 at index 4, wait 1. Index 4 (7): nothing higher after it, 0. Index 5 (2): 6 at index 6, wait 1. Index 6: last reading, 0. This gives [1, 3, 2, 1, 0, 1, 0].

(a) Idea. Scan the readings from left to right and keep a stack of the indices of the readings that are still waiting, that is, no higher reading has appeared after them yet. When the reading ii arrives, every waiting reading jj with a strictly lower level has found its answer: result[j] = i - j, and jj leaves the stack. Then ii itself starts waiting and is pushed.

Invariant. Before processing index ii: the stack contains exactly the indices j<ij < i that have no strictly higher reading among j+1,…,i−1j+1, \dots, i-1, ordered by increasing index from the bottom to the top, and their levels are non-increasing from the bottom to the top; for every j<ij < i not in the stack, result[j] is already its final value. This gives the stopping rule: if the top has level ≥\ge level[i], all the indices below have level ≥\ge the top, so none of them is lower than level[i] and we can stop popping. After the pops, the top has level ≥\ge level[i], so pushing ii keeps the levels non-increasing, and the invariant holds for i+1i + 1. At the end the indices still in the stack never met a higher reading and keep the value 00 of the initialisation.

(b) Code.

java
static int[] waitHours(int[] level) {
    int n = level.length;
    int[] result = new int[n];            // all 0: "no higher reading"
    int[] stack = new int[n];             // indices of the waiting readings
    int top = 0;                          // number of indices in the stack
    for (int i = 0; i < n; i++) {
        // the reading i answers every waiting reading that is strictly lower
        while (top > 0 && level[stack[top - 1]] < level[i]) {
            int j = stack[--top];
            result[j] = i - j;
        }
        stack[top++] = i;                 // now i waits for a higher reading
    }
    return result;                        // the indices left in the stack keep 0
}

The stack is a plain array with a counter top, which is enough (no import is needed; ArrayDeque<Integer> would do the same).

(c) Complexity. The for loop runs nn times. The index ii is pushed exactly once (one push per iteration, nn pushes) and popped at most once, so the total number of iterations of the while loop that pop is at most nn. The tests that stop the while are at most one per iteration of the for, so at most nn in total. All together at most about 3n3n elementary steps: Θ(n)\Theta(n) time for every input, even if one single iteration of the for may pop many indices (an amortised argument, as in the doubling of the array of a heap 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 →). Space: the arrays result and stack of length nn, so Θ(n)\Theta(n) extra space.

Tests that were run (JDK 21, javac and java):

input output
[3, 5, 4, 4, 7, 2, 6] [1, 3, 2, 1, 0, 1, 0]
[9, 8, 7, 6] [0, 0, 0, 0]
[2, 2, 2, 5] [3, 2, 1, 0]
[4] (one reading) [0]
[1, 2, 3, 4, 5] (increasing) [1, 1, 1, 1, 0]
[5, 4, 3, 2, 1] (decreasing) [0, 0, 0, 0, 0]
[0, 0, 0] (all equal) [0, 0, 0]
[1000000, 0, 1000000, 0] [0, 1, 0, 0]

Then 20 000 random arrays (length 1 to 30, levels 0 to 12, many repeated values) were compared with the O(n2)O(n^2) reference solution: all results were equal. Counting the operations of the algorithm on random arrays gave, for n=10,100,1000,100 000n = 10, 100, 1000, 100\,000: 10,100,1000,100 00010, 100, 1000, 100\,000 pushes and at most 14,191,1985,199 96914, 191, 1985, 199\,969 comparisons in the while tests, always below 2n2n. Timing on a strictly decreasing array (the hardest for the naive solution): the stack solution takes about 0.3 ms for n=105n = 10^5 and about 6 ms for n=106n = 10^6, while the naive double loop takes about 1.2 s already for n=105n = 10^5 (about 100 times longer for n=106n = 10^6).

Typical mistakes: popping when the levels are equal (<= instead of <): then [2, 2, 2, 5] still works but [3, 3] would give [1, 0] instead of [0, 0]; storing the levels instead of the indices in the stack (the distance i - j is lost); forgetting that the indices left in the stack must give 00; scanning for each index until a higher reading is found, which is O(n2)O(n^2) on a decreasing array.

Self-assessment grid
Exercise Points What must be there for full marks Typical mistakes
1 3 exact counts n(n+1)n(n+1) and n(⌊log⁡2n⌋+1)n(\lfloor \log_2 n \rfloor + 1) with the Θ\Theta order; explicit cc and n0n_0 for O(n2)O(n^2); contradiction argument for n2∉O(n)n^2 \notin O(n) wrong number of iterations of the halving loop; cc depending on nn; a few numerical examples instead of a proof
2 4 base case n=1n = 1; three cases on the root (strong induction, two subtrees); the counts n1=2n_1 = 2 in (c) and "no" in (d) with the reason n=2n0−1n = 2n_0 - 1 forgetting the one-child case; proving only for proper trees; mixing the sizes of the subtrees with the counts
3 4 three correct sequences; tree of (b) rebuilt step by step with its postorder; counterexample for preorder plus postorder right child before left child; wrong split of the preorder; claiming that preorder and postorder always suffice
4 5 the array and the swaps after each of the 8 inserts; the 4 operations of (c) with the returned keys; the bound 9 for both operations with the reason (height) and a case that reaches it swapping with the larger child; non-strict comparison; wrong indices of the children; height without the floor
5 6 header with input and output and the pair (b,h)(b, h); base case and initial call; use of the returned pair; Θ(n)\Theta(n) with one call per node; correct trace of the 8 calls only the root is tested; 00 instead of −1-1 for a missing child; calling height at every node; discarding the returned values
6 8 idea with the stack of waiting indices and its invariant; correct Java code with the strict comparison; Θ(n)\Theta(n) time by the push and pop count <= instead of <; values instead of indices on the stack; O(n2)O(n^2) double loop

For extra practice on the same topics see 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 →, 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 →, Binary Tree Traversals and Expression TreesInorder visits the left subtree, the node, then the right subtree; on the parse tree of an arithmetic expression postorder evaluates the expression and inorder rebuilds the fully parenthesized infix form, both in linear time.Binary Tree Traversals and Expression Trees →, 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 → and 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 →.