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 , and give its order of growth with .
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:
- prove that , giving explicit constants and ;
- prove that .
Show the result
(a) Fragment A: executions, so . Fragment B: executions, so .
(b) 1. For example , : for all . 2. Whatever and are chosen, fails for .
Show the full solution
(a) Fragment A. For a fixed the inner loop runs 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 →):
Since for , the count is . The bound holds for every , because the loops do not depend on the data.
Fragment B. The inner loop always executes times. The outer loop starts with and halves (integer part) until it becomes : the values are . The value is at least exactly when , that is . So there are iterations and the count is
For we have , so (the last step uses ). Hence .
Check: gives for B and for A; gives for B and for A (both confirmed by running the loops).
Typical mistakes: counting for A (forgetting the factor 2, which does not change but changes the exact count); writing iterations for B instead of (the iteration with counts); thinking B is because it has two nested loops.
(b) 1. Recall the definition: if there are constants and such that for all . Take (the dominant term) and write each lower-order term as a multiple of . For we have and , so
The inequality holds for all , so and work. (Other choices are also correct, for instance and , because means , which holds for ; 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 : there are and with for every . Dividing by gives for every . This is false for the integer , which is and larger than . Contradiction, so .
Typical mistakes: choosing or that depend on ; proving the inequality for some values of only; for part 2, trying a few numbers instead of showing that no constants work.
Exercise 2 (points 4)
Let 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 be the number of nodes, the number of leaves, the number of nodes with exactly one child and the number of nodes with exactly two children.
(a) Prove by induction on that .
(b) Deduce that in a proper binary tree with nodes and leaves, .
(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) holds for every non-empty binary tree (induction on , three cases on the root: base case , root with one child, root with two children).
(b) .
(c) ; the tree is not proper.
(d) No.
Show the full solution
(a) The claim : every binary tree with nodes satisfies . 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, ) and a step that assumes the claim for all sizes up to .
- Base case . The tree is a single node: it is a leaf, so , and there are no nodes with two children, so . Indeed .
- Inductive step. Fix and assume for all . Take a tree with nodes. Its root is not a leaf (a leaf alone would give ), so has one or two children. Look at what contributes to the three counts: a node with one child contributes to , a node with two children contributes to .
- Case 1: has one child. Removing leaves a tree with nodes (the subtree of the child). The root adds nothing to or to , and every other node keeps its number of children, so and . By the hypothesis on : .
- Case 2: has two children. The two subtrees are non-empty binary trees with nodes and , so both have at most nodes and the hypothesis applies to both. The leaves of are the leaves of and of : . The nodes with two children are those of , those of , and the root: . Then
In both cases holds, which proves the claim for every . (Strong induction is needed in Case 2, because the two subtrees have different sizes.) Computer check: the equality holds for all binary tree shapes with up to 10 nodes.
(b) A proper binary tree has no node with exactly one child: . So the nodes are leaves or nodes with two children, , hence . Put this into (a), with : 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 with , and (by (a)): Since , the tree is not proper.
(d) In a proper tree , so . With leaves we get , not . 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 and 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 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 , always visiting the left child before the right child.
A
/ \
B C
/ \ /
D E F
\ / \
G H I(b) A binary tree with 8 nodes has preorder S K N Q Z V R T and inorder N K Q Z S R T V. Draw 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.
- 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).
- 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.
- 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.
- 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 TPostorder (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 BOnly the inorder tells them apart: B A for the first tree and A B for the second. For the tree 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 with level numbering (the root is in , the children of are in and ). 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 , while the parent's key is larger. removeMin returns , moves the Last entry into 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 before bubbling):
insert(14): cell 0, no parent: [14].insert(9): cell 1, parent cell 0 holds 14 > 9, swap: [9, 14]. 1 swap.insert(21): cell 2, parent 9 < 21, stop: [9, 14, 21]. 0 swaps.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.insert(17): cell 4, parent cell 1 (9 < 17), stop: [5, 9, 21, 14, 17]. 0 swaps.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.insert(11): cell 6, parent cell 2 (5 < 11), stop: [3, 9, 5, 14, 17, 21, 11]. 0 swaps.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 is a node, with children in cells and : 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)
removeMin(): returns . 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.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.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.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 → ().
insert: after the insertion the heap has 1001 entries, so its height is , 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 (sorted, hence a heap) the callinsert(0)makes exactly 9 swaps.removeMin: after the removal there are 999 entries, height . 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 : 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 ). 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 and ; after the removal forgetting that the array has one entry fewer; writing the height as without the floor.
Exercise 5 (points 6)
A binary tree 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 is not empty). The height of a leaf is and the height of a missing child is . is balanced if for every node of the heights of the left and of the right subtree of (a missing subtree has height ) differ by at most 1.
(a) Design a recursive algorithm heightBalanced(T, v) that returns, for the subtree , 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 of nodes of . For full marks it must be .
(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 WShow the result
(a) heightBalanced(T, v) returns the pair : = " is balanced", = height of . Initial call heightBalanced(T, T.root()), first component of the answer.
(b) 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 is "good" if the heights of its two subtrees differ by at most 1, and is balanced if is good and both subtrees are balanced. The test at needs the heights of the two subtrees, and the height of itself (for its parent) is of them. So this is a postorder pattern (first the children, then the visit of , 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()). tells whether is balanced and is the height of . Base case: a leaf has no children, the two if do nothing, so it returns (true, 0) (since and ). 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 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 . 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 at every node and, in total, : on a perfect tree and 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 nodes, one per node of . The calls are made whatever the values of and : 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 twoifat most two tests: . - Total. , for every tree: best and worst case coincide. In the notation of the notes, it is the postorder cost with . 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:
- S is a leaf: (true, 0).
- R has only the left child S with and ; , so = true and : (true, 1).
- T is a leaf: (true, 0).
- Q has children R (height 1) and T (height 0): difference 1, both balanced: (true, 2).
- W is a leaf: (true, 0).
- V has the left child W: , : (true, 1).
- U has the left child V with height 1 and no right child: , so = false and : (false, 2).
- P has the left child Q with height 2 and the right child U with height 2: the heights are equal, but = false, so = false and : (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 instead of 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 .
Exercise 6 (points 8)
Part 3, programming (proposed part). Rising tide. A tide gauge records the water level once per hour and stores the readings in an array level. For every hour you want to know how many hours you must wait to see a strictly higher level than at hour .
Write in Java the method
static int[] waitHours(int[] level)that returns an array result of length where result[i] is the smallest such that and level[i + d] > level[i], or if no later reading is higher.
Constraints: and . Required complexity: time and extra space. A solution that compares every reading with all the following ones takes 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 (each index is pushed once and popped at most once), extra space (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 arrives, every waiting reading with a strictly lower level has found its answer: result[j] = i - j, and leaves the stack. Then itself starts waiting and is pushed.
Invariant. Before processing index : the stack contains exactly the indices that have no strictly higher reading among , ordered by increasing index from the bottom to the top, and their levels are non-increasing from the bottom to the top; for every not in the stack, result[j] is already its final value. This gives the stopping rule: if the top has level level[i], all the indices below have level the top, so none of them is lower than level[i] and we can stop popping. After the pops, the top has level level[i], so pushing keeps the levels non-increasing, and the invariant holds for . At the end the indices still in the stack never met a higher reading and keep the value of the initialisation.
(b) Code.
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 times. The index is pushed exactly once (one push per iteration, pushes) and popped at most once, so the total number of iterations of the while loop that pop is at most . The tests that stop the while are at most one per iteration of the for, so at most in total. All together at most about elementary steps: 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 , so 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 reference solution: all results were equal. Counting the operations of the algorithm on random arrays gave, for : pushes and at most comparisons in the while tests, always below . Timing on a strictly decreasing array (the hardest for the naive solution): the stack solution takes about 0.3 ms for and about 6 ms for , while the naive double loop takes about 1.2 s already for (about 100 times longer for ).
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 ; scanning for each index until a higher reading is found, which is on a decreasing array.
Self-assessment grid
| Exercise | Points | What must be there for full marks | Typical mistakes |
|---|---|---|---|
| 1 | 3 | exact counts and with the order; explicit and for ; contradiction argument for | wrong number of iterations of the halving loop; depending on ; a few numerical examples instead of a proof |
| 2 | 4 | base case ; three cases on the root (strong induction, two subtrees); the counts in (c) and "no" in (d) with the reason | 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 ; base case and initial call; use of the returned pair; with one call per node; correct trace of the 8 calls | only the root is tested; instead of 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; time by the push and pop count | <= instead of <; values instead of indices on the stack; 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 →.