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

Data Structures and Algorithms - Mock Exam 3

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 Italian course (Dati e Algoritmi, UniPD); it is a simulation, not a real paper. The official examples have two parts: a first part of short questions of analysis and theory (here exercises 1-3, 3 + 4 + 4 = 11 points) and a second part with the execution of algorithms on data structures and the design of an algorithm in pseudocode with its analysis (here exercises 4-5, 5 + 6 = 11 points). The official sheets do not state the duration: 150 minutes for the two parts is a proposal. Since the real exam also has a programming part, exercise 6 (a LeetCode-style problem in Java) is an additional proposal, with 10 points and 60 more minutes at the computer: it is not taken from the official examples. No material allowed.

The topics of this mock are: comparison of orders of growth, best and worst case analysis, hash tables (compression function, separate chaining, load factor, rehashing), a binary tree in array representation, and maps. Linked lists with iterators, binary search trees and open addressing (linear probing) are not developed in the course notes, so they are replaced by the array representation of a binary tree (exercise 4) and by the list-based map (exercise 3, part c). Pseudocode follows the notation of 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 →; all the results were checked by running the algorithms (Python for exercises 1-5, Java 21 for exercise 6).

Exercise 1 (points 3)

Consider the following functions of n≥2n \ge 2:

f1(n)=log⁡2 ⁣(n10),f2(n)=(log⁡2n)3,f3(n)=nlog⁡2n,f4(n)=7n+100n,f_1(n) = \log_2\!\big(n^{10}\big), \quad f_2(n) = (\log_2 n)^3, \quad f_3(n) = n \log_2 n, \quad f_4(n) = 7n + 100\sqrt{n},

f5(n)=n3/2,f6(n)=2n/10,f7(n)=5ln⁡n.f_5(n) = n^{3/2}, \quad f_6(n) = 2^{n/10}, \quad f_7(n) = 5 \ln n.

(a) (2 points) Group the functions into classes of functions with the same order of growth (Θ\Theta), and list the classes in increasing order of growth. Write g≺hg \prec h for g∈o(h)g \in o(h).

(b) (1 point) Prove from the definition of Θ\Theta that f4(n)∈Θ(n)f_4(n) \in \Theta(n), giving explicit constants c′c', c′′c'' and n0n_0.

Show the result

(a) {f1,f7}≺{f2}≺{f4}≺{f3}≺{f5}≺{f6}\{f_1, f_7\} \prec \{f_2\} \prec \{f_4\} \prec \{f_3\} \prec \{f_5\} \prec \{f_6\}, where f1,f7∈Θ(log⁡n)f_1, f_7 \in \Theta(\log n), f2∈Θ((log⁡n)3)f_2 \in \Theta((\log n)^3), f4∈Θ(n)f_4 \in \Theta(n), f3∈Θ(nlog⁡n)f_3 \in \Theta(n \log n), f5∈Θ(n3/2)f_5 \in \Theta(n^{3/2}), f6f_6 exponential.

(b) 7n≤f4(n)≤107 n7n \le f_4(n) \le 107\, n for all n≥1n \ge 1: c′=7c' = 7, c′′=107c'' = 107, n0=1n_0 = 1.

Show the full solution

(a) Use the properties of growth rates in 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 →.

  • f1f_1 and f7f_7. f1(n)=10log⁡2nf_1(n) = 10 \log_2 n and f7(n)=5ln⁡n=(5ln⁡2)log⁡2nf_7(n) = 5 \ln n = (5 \ln 2)\log_2 n: both are a constant times log⁡2n\log_2 n (the base of a logarithm does not matter inside Θ\Theta), so f1,f7∈Θ(log⁡n)f_1, f_7 \in \Theta(\log n) and they form one class.
  • f1≺f2f_1 \prec f_2. f1/f2=10/(log⁡2n)2→0f_1/f_2 = 10/(\log_2 n)^2 \to 0.
  • f2≺f4f_2 \prec f_4. Polylogarithmic against polynomial: (log⁡2n)3∈o(n)(\log_2 n)^3 \in o(n), and f4∈Θ(n)f_4 \in \Theta(n) by part (b).
  • f4≺f3f_4 \prec f_3. f3/n=log⁡2n→∞f_3/n = \log_2 n \to \infty, so n∈o(nlog⁡n)n \in o(n \log n). The lower-order term 100n100\sqrt{n} is absorbed by 7n7n and does not change the class.
  • f3≺f5f_3 \prec f_5. f3/f5=log⁡2n/n→0f_3/f_5 = \log_2 n / \sqrt{n} \to 0 (polylogarithmic against polynomial, with exponent h=1/2h = 1/2).
  • f5≺f6f_5 \prec f_6. f6(n)=(21/10)n=anf_6(n) = (2^{1/10})^n = a^n with a=21/10>1a = 2^{1/10} > 1, and every polynomial is in o(an)o(a^n): n3/2∈o(an)n^{3/2} \in o(a^n).

Typical mistakes: thinking that the small factor 1/101/10 in the exponent makes 2n/102^{n/10} "almost linear" (it is still exponential, and beats every polynomial); putting f3f_3 before f4f_4; treating log⁡2n\log_2 n and ln⁡n\ln n as different classes.

(b) The definition (f∈Θ(g)f \in \Theta(g) if there are c′,c′′>0c', c'' > 0 and n0≥1n_0 \ge 1 with c′g(n)≤f(n)≤c′′g(n)c' g(n) \le f(n) \le c'' g(n) for all n≥n0n \ge n_0) asks for two bounds, each proved with the method of the notes (rewrite the lower-order term as a multiple of the dominant one).

  • Lower bound. 100n≥0100\sqrt{n} \ge 0, so f4(n)=7n+100n≥7nf_4(n) = 7n + 100\sqrt{n} \ge 7n. Hence c′=7c' = 7.
  • Upper bound. For n≥1n \ge 1 we have n≤n\sqrt{n} \le n, so f4(n)≤7n+100n=107 nf_4(n) \le 7n + 100n = 107\, n. Hence c′′=107c'' = 107.

Both hold for every n≥1n \ge 1, so n0=1n_0 = 1 and f4∈Θ(n)f_4 \in \Theta(n). Typical mistake: proving only the upper bound, which gives O(n)O(n) but not Θ(n)\Theta(n).

Exercise 2 (points 4)

Consider the following algorithm.

Algorithm shrinkScan(A)
Input: array A[0 ÷ n-1] of n ≥ 1 integers
Output: the number of cells equal to 0 met before the algorithm stops
c ← 0;
m ← n;
while (m ≥ 1) do {
    j ← 0;
    while (j < m) do {
        if (A[j] < 0) then return c;
        if (A[j] = 0) then c ← c + 1;
        j ← j + 1;
    }
    m ← ⌊m/2⌋;
}
return c

(a) (1 point) Execute shrinkScan on A=[3,0,2,0,5]A = [3, 0, 2, 0, 5] (n=5n = 5). Give the returned value and the number of times the test A[j] < 0 is evaluated.

(b) (1 point) Describe an instance of each size nn that is a best case for the algorithm and give the best-case time as a Θ\Theta.

(c) (2 points) A student says: "the outer loop makes about log⁡2n\log_2 n iterations and each one can make up to nn steps, so the worst-case time complexity is Θ(nlog⁡n)\Theta(n \log n)". Determine the worst-case time complexity of shrinkScan and say what is wrong with the claim.

Show the result

(a) Returned value 33; the test A[j] < 0 is evaluated 88 times.

(b) Any instance with A[0]<0A[0] < 0: the algorithm stops after one test, Θ(1)\Theta(1).

(c) The worst case is Θ(n)\Theta(n) (for instances without negative cells the test is evaluated 2n−(number of 1-bits of n)2n - (\text{number of 1-bits of } n) times, between nn and 2n2n). The claim is wrong because the inner loop makes mm steps with m=n,n/2,n/4,…m = n, n/2, n/4, \dots, not nn steps every time: the sum is a geometric series, below 2n2n.

Show the full solution

(a) Trace (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 notation).

outer pass mm cells read tests A[j] < 0 zeros found cc after the pass
1 5 3,0,2,0,53, 0, 2, 0, 5 5 2 2
2 2 3,03, 0 2 1 3
3 1 33 1 0 3

Then m=⌊1/2⌋=0m = \lfloor 1/2 \rfloor = 0, the outer loop ends and the algorithm returns c=3c = 3. Tests: 5+2+1=85 + 2 + 1 = 8. No cell is negative, so the early return never fires.

(b) The only way to leave the algorithm before the loops end is the return on a negative cell. If A[0]<0A[0] < 0 (for example A=[−1,… ]A = [-1, \dots]) it is reached at the very first test of the first pass: a constant number of operations for the initialisation, one test, and the return. So tbest(n)∈Θ(1)t_{\text{best}}(n) \in \Theta(1), whatever the size. Note that this is a statement about the best instance; the complexity tA(n)t_A(n) of the notes is the worst case (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 →).

(c) The worst case needs an upper bound valid for every instance and one instance that reaches it.

  • Upper bound (every instance). Pass k=0,1,2,…k = 0, 1, 2, \dots has mk=⌊n/2k⌋m_k = \lfloor n/2^k \rfloor and its inner loop makes at most mkm_k iterations, each of constant cost ≤c\le c. The outer loop runs for k=0,…,⌊log⁡2n⌋k = 0, \dots, \lfloor \log_2 n \rfloor, so the total is at most c∑k=0⌊log⁡2n⌋n2k  ≤  c n∑k=0∞12k=2c n,c \sum_{k=0}^{\lfloor \log_2 n \rfloor} \frac{n}{2^k} \;\le\; c\, n \sum_{k=0}^{\infty} \frac{1}{2^k} = 2c\, n, plus a constant cost per outer pass, which adds O(log⁡n)O(\log n). Hence tA(n)∈O(n)t_A(n) \in O(n).
  • Lower bound (one instance). Take AA with no negative cell, for instance all cells equal to 11. The first pass alone makes nn iterations: at least nn tests, so tA(n)∈Ω(n)t_A(n) \in \Omega(n).

Together, tA(n)∈Θ(n)t_A(n) \in \Theta(n). The exact number of tests on the instance with no negative cell is ∑k≥0⌊n/2k⌋=2n−(number of 1-bits of n)\sum_{k \ge 0} \lfloor n/2^k \rfloor = 2n - (\text{number of 1-bits of } n): for n=8,64,1024n = 8, 64, 1024 it is 15,127,204715, 127, 2047 (checked by running the algorithm).

Where the student goes wrong: "number of passes times the cost of the longest pass" is a valid upper bound, O(nlog⁡n)O(n \log n), but it is not tight, because the passes are not all long. A correct analysis sums the actual cost of each pass. Typical mistakes: saying "the complexity is Θ(n)\Theta(n)" without specifying worst case, when the best case is Θ(1)\Theta(1); giving the best case as Θ(n)\Theta(n).

Exercise 3 (points 4)

A map is implemented with a hash table with separate chaining. The keys are integers, so the hash code is the key itself, and the compression function is MAD:

hN(k)=((3k+5) mod 17) mod N,h_N(k) = \big((3k + 5) \bmod 17\big) \bmod N,

where NN is the current number of buckets. The table is initially empty with N=5N = 5. After each put that inserts a new key, if the load factor λ=n/N\lambda = n/N is greater than 0.750.75 the table is rehashed: the new capacity is the smallest prime number ≥2N\ge 2N, the same formula hNh_{N} is used with the new NN, and the old entries are reinserted scanning the old buckets from 00 upwards, each chain from its first to its last entry. A new entry is always appended at the end of its chain. The keys are put in this order:

85, 15, 48, 13, 44, 70, 86, 59.85,\ 15,\ 48,\ 13,\ 44,\ 70,\ 86,\ 59.

(a) (1 point) Compute (3k+5) mod 17(3k + 5) \bmod 17, h5(k)h_5(k) and h11(k)h_{11}(k) for each of the eight keys.

(b) (2 points) Show the content of the buckets after the fourth put, after the rehash that it triggers, and after the eighth put.

(c) (1 point) Give the final load factor and the number of key comparisons made by the eight put operations (the reinsertions of a rehash are not counted). How many comparisons would the same eight put make on a map implemented with an unsorted list? Would a ninth put of a new key trigger a rehash, and what must be changed in the formula if it does?

Show the result

(a)

kk 85 15 48 13 44 70 86 59
(3k+5) mod 17(3k+5) \bmod 17 5 16 13 10 1 11 8 12
h5(k)h_5(k) 0 1 3 0 1 1 3 2
h11(k)h_{11}(k) 5 5 2 10 1 0 8 1

(b) After the fourth put (N=5N = 5, λ=0.8\lambda = 0.8): bucket 0: 85,1385, 13; bucket 1: 1515; bucket 3: 4848; buckets 2, 4 empty. Rehash to N=11N = 11: bucket 2: 4848; bucket 5: 85,1585, 15; bucket 10: 1313. After the eighth put: bucket 0: 7070; bucket 1: 44,5944, 59; bucket 2: 4848; bucket 5: 85,1585, 15; bucket 8: 8686; bucket 10: 1313; buckets 3, 4, 6, 7, 9 empty.

(c) λ=8/11≈0.727\lambda = 8/11 \approx 0.727; 22 comparisons for the hash table, 0+1+⋯+7=280 + 1 + \dots + 7 = 28 for the list; the ninth put gives λ=9/11≈0.818>0.75\lambda = 9/11 \approx 0.818 > 0.75, so a rehash to N=23N = 23 happens, and since p=17<23p = 17 < 23 the prime pp of the MAD method must be replaced by a prime greater than 2323 (for instance 2929).

Show the full solution

(a) For each key compute 3k+53k + 5, reduce modulo 1717 (the MAD step, see Hash TablesA hash table implements a map by sending each key through a hash function to one of N buckets, handling collisions with separate chaining, and it gives expected O(1 + load factor) time per operation but Theta(n) in the worst case.Hash Tables →), then reduce modulo NN. For example k=85k = 85: 3⋅85+5=260=15⋅17+53 \cdot 85 + 5 = 260 = 15 \cdot 17 + 5, so the remainder is 55; then 5 mod 5=05 \bmod 5 = 0 and 5 mod 11=55 \bmod 11 = 5. For k=15k = 15: 50=2⋅17+1650 = 2 \cdot 17 + 16, remainder 1616; 16 mod 5=116 \bmod 5 = 1, 16 mod 11=516 \bmod 11 = 5. The other columns are obtained in the same way (the table above).

(b) Puts with N=5N = 5 (h5h_5 row of the table):

  • 85→85 \to bucket 0; 15→15 \to bucket 1; 48→48 \to bucket 3 (n=3n = 3, λ=0.6≤0.75\lambda = 0.6 \le 0.75, no rehash).
  • 13→13 \to bucket 0, which already holds 8585: the chain becomes 85,1385, 13 (the new entry goes at the end). Now n=4n = 4, λ=4/5=0.8>0.75\lambda = 4/5 = 0.8 > 0.75: rehash.
N = 5          bucket 0: 85, 13    bucket 1: 15    bucket 2: -    bucket 3: 48    bucket 4: -

Rehash: the new capacity is the smallest prime ≥2N=10\ge 2N = 10, that is 1111. Scan the old buckets in order, so the entries are reinserted in the order 85,13,15,4885, 13, 15, 48, each at the position given by h11h_{11}: 85→585 \to 5, 13→1013 \to 10, 15→515 \to 5 (appended after 8585), 48→248 \to 2. No search is needed, because the keys are already known to be distinct.

N = 11   0:-   1:-   2:48   3:-   4:-   5:85,15   6:-   7:-   8:-   9:-   10:13

Remaining puts with N=11N = 11 (h11h_{11} row): 44→144 \to 1; 70→070 \to 0; 86→886 \to 8; 59→159 \to 1, behind 4444. After each of them λ≤8/11<0.75\lambda \le 8/11 < 0.75, so there is no further rehash. Final table:

N = 11   0:70   1:44,59   2:48   3:-   4:-   5:85,15   6:-   7:-   8:86   9:-   10:13

Typical mistakes: reinserting the old entries in input order instead of bucket order (here 1515 would be placed before 8585, giving the chain 15,8515, 85 in bucket 5); taking the new size 1010 instead of the prime 1111; forgetting that the new entry is appended at the end of the chain.

(c) n=8n = 8, N=11N = 11: λ=8/11≈0.727\lambda = 8/11 \approx 0.727.

Comparisons. A put searches the chain of its bucket for the key before appending. Only two puts find a non-empty chain: 1313 meets 8585 (1 comparison) and 5959 meets 4444 (1 comparison). All the others find an empty chain. Total: 22 comparisons.

List-based map (MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps →). Every put must scan all the existing entries to check that the key is new: the ii-th put makes i−1i - 1 comparisons, in total 0+1+⋯+7=280 + 1 + \dots + 7 = 28 (for nn keys Θ(n2)\Theta(n^2)). With the hash table the expected cost of each operation is O(1+λ)O(1 + \lambda), constant for bounded λ\lambda; the worst case, all keys in one bucket, is Θ(n)\Theta(n) per operation, like the list.

Ninth put. A new key gives n=9n = 9 and λ=9/11≈0.818>0.75\lambda = 9/11 \approx 0.818 > 0.75, so a rehash to the smallest prime ≥22\ge 22, that is N=23N = 23, is needed. The MAD method requires a prime p>Np > N; with p=17p = 17 we would have p<23p < 23 and the buckets 17,…,2217, \dots, 22 could never be reached, so pp must be replaced (for instance p=29p = 29).

Exercise 4 (points 5)

A binary tree TT with nn nodes is stored in an array A[0÷M−1]A[0 \div M-1] with level numbering: the root is A[0]A[0], the left child of A[i]A[i] is A[2i+1]A[2i + 1] and the right child is A[2i+2]A[2i + 2]. A cell holds the key of the node, or null if there is no node at that position; a child index ≥M\ge M means that the node has no child there. All the nodes have integer keys. A node vv is visible if its key is strictly greater than the key of every proper ancestor of vv (the root is always visible).

(a) (1 point) Draw the tree stored in A=[8, 5, 11, 3, 9, null, 14, null, null, 10, 6, null, null, 12, 17]A = [8,\ 5,\ 11,\ 3,\ 9,\ \text{null},\ 14,\ \text{null},\ \text{null},\ 10,\ 6,\ \text{null},\ \text{null},\ 12,\ 17] and say which nodes are visible.

(b) (2 points) Write in pseudocode a recursive algorithm countVisible that, given AA and MM, returns the number of visible nodes. Specify input and output of the generic call and the initial call.

(c) (2 points) Analyse the time complexity of countVisible as a function of nn. Is it Θ(M)\Theta(M)? How large can MM be with respect to nn?

Show the result

(a) Visible nodes: 8,11,9,14,10,178, 11, 9, 14, 10, 17 (6 nodes). Not visible: 5,3,6,125, 3, 6, 12.

(b) Initial call countVisible(A, M, 0, -∞); it returns 66 on the array of part (a).

(c) Θ(n)\Theta(n): exactly 2n+12n + 1 calls (2121 for n=10n = 10), each of constant cost. It is not Θ(M)\Theta(M): MM can be exponential in nn (M≤2h+1−1M \le 2^{h+1} - 1, up to about 2n2^n for a skewed tree).

Show the full solution

(a) Children of A[i]A[i] are A[2i+1]A[2i+1] and A[2i+2]A[2i+2] (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 →, level numbering, here applied to a generic binary tree as in 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 →): A[0]=8A[0] = 8 has children A[1]=5A[1] = 5 and A[2]=11A[2] = 11; A[1]A[1] has children A[3]=3A[3] = 3 and A[4]=9A[4] = 9; A[2]A[2] has children A[5]=nullA[5] = \text{null} and A[6]=14A[6] = 14; A[3]A[3] has no children (A[7]A[7], A[8]A[8] are null); A[4]A[4] has children A[9]=10A[9] = 10 and A[10]=6A[10] = 6; A[5]A[5] is null so A[11]A[11], A[12]A[12] are null; A[6]A[6] has children A[13]=12A[13] = 12 and A[14]=17A[14] = 17.

              8
           /     \
         5         11
        / \           \
       3   9           14
          / \         /  \
        10   6      12    17

Visibility: the maximum key among the proper ancestors is −∞-\infty for 88 (visible); 88 for 55 and 1111 (so 55 is not visible, 1111 is); the ancestors of 33 and 99 are 55 and 88, maximum 88, so 33 is not visible and 9>89 > 8 is; the ancestors of 1010 and 66 are 9,5,89, 5, 8, maximum 99, so 1010 is visible and 66 is not; the ancestors of 1414 are 11,811, 8, maximum 1111, so 1414 is visible; the ancestors of 1212 and 1717 are 14,11,814, 11, 8, maximum 1414, so 1717 is visible and 1212 is not. Visible: 8,11,9,14,10,178, 11, 9, 14, 10, 17.

(b) It is a preorder-like visit (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 the node is processed before its subtrees and carries the information of the path (the maximum key found so far). The parameter best is exactly what a node needs to know about its ancestors.

Algorithm countVisible(A, M, i, best)
Input: array A[0 ÷ M-1] storing a binary tree with level numbering (null = no node),
       index i ≥ 0 of a position, best = maximum key among the proper ancestors
       of position i (-∞ if i is the root)
Output: number of visible nodes of the subtree whose root is at position i
if (i ≥ M) OR (A[i] = null) then return 0;          // BASE CASE: no node here
c ← 0;
if (A[i] > best) then {                              // visible: key above all ancestors
    c ← 1;
    best ← A[i];                                     // the maximum for the children
}
l ← countVisible(A, M, 2i + 1, best);                // left subtree
r ← countVisible(A, M, 2i + 2, best);                // right subtree
return c + l + r

The initial call is countVisible(A, M, 0, -∞). As required for recursive algorithms (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 →, 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 →), every recursive call has the same signature as the header, the base case is explicit and the returned values are stored in variables before being used. Execution on the array of (a): c=1c = 1 at positions 0,2,4,6,9,140, 2, 4, 6, 9, 14, and c=0c = 0 elsewhere, so the result is 66.

(c) Use the recursion tree (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 →). Every node of TT (a non-null cell) executes the body once and makes exactly two recursive calls, on the two child positions, whether or not the children exist. A call on a null cell or on an index ≥M\ge M stops in the base case and makes no further call. So:

  • there are nn calls on existing nodes (one per node) and, besides the first call on the root, every other call is a child call of an existing node: the total number of calls is 1+2n1 + 2n (for n=10n = 10: 2121 calls, 1010 on nodes and 1111 on null positions; checked by running the algorithm);
  • each call costs Θ(1)\Theta(1) (two comparisons, a few assignments, the sum).

Total: Θ(n)\Theta(n). The array has MM cells, but the algorithm never visits the cells that are not children of an existing node: the cost is independent of MM, so it is not Θ(M)\Theta(M).

For a binary tree of height hh, level numbering needs M≤2h+1−1M \le 2^{h+1} - 1 cells, and hh can be as large as n−1n - 1 (a path in which every node has one child), so MM can be of order 2n2^n while nn is small (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 →: the array of a skewed tree grows exponentially). In that case an algorithm that scans the whole array would be exponential in nn, while countVisible stays linear. Typical mistakes: writing Θ(M)\Theta(M) or Θ(2h)\Theta(2^h) for the cost; stopping the recursion only when i≥Mi \ge M and forgetting the null test (it would read a null as a key); updating best after the recursive calls instead of before them; using ≥\ge instead of >> in the visibility test (equal keys would then count as visible).

Exercise 5 (points 6)

Let S[0÷n−1]S[0 \div n-1] be a sequence of n≥0n \ge 0 integers, possibly with repetitions. Position jj is a repetition if S[j]=S[i]S[j] = S[i] for some i<ji < j. For example, in S=[7,3,9,3,7]S = [7, 3, 9, 3, 7] the positions 33 and 44 are repetitions.

(a) (3 points) Design an algorithm firstRepeat that returns the smallest position that is a repetition, or −1-1 if all the elements are distinct. The algorithm must use a map MM through the methods get and put of the Map interface only, and must make a single pass over SS. State precisely input and output.

(b) (2 points) Analyse the time complexity of firstRepeat: best case, average case with a hash table with separate chaining (assume a uniform hash function and a load factor kept below a constant), and worst case. What changes if MM is implemented with an unsorted list?

(c) (1 point) Give a loop invariant that proves the correctness of the algorithm.

Show the result

(a) firstRepeat returns jj, the first position whose key is already in MM, otherwise −1-1 (on [7,3,9,3,7][7, 3, 9, 3, 7] it returns 33).

(b) Best case Θ(1)\Theta(1) (for example S[0]=S[1]S[0] = S[1]); average case Θ(n)\Theta(n) for distinct elements; worst case Θ(n2)\Theta(n^2) (all keys in one bucket); with an unsorted list Θ(n2)\Theta(n^2) in the worst case.

(c) At the start of iteration jj, MM contains exactly the values of S[0÷j−1]S[0 \div j-1], and no position <j< j is a repetition.

Show the full solution

(a) Idea: scan SS from left to right keeping in MM the values already seen (key = value of SS, value = its position). A position jj is a repetition exactly when S[j]S[j] is already a key of MM; the first time this happens we have found the smallest repetition and we can stop. See MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps → for the interface: get returns null if the key is absent, so the stored value must never be null: the position works.

Algorithm firstRepeat(S)
Input: array S[0 ÷ n-1] of n ≥ 0 integers
Output: the smallest j such that S[j] = S[i] for some i < j, or -1 if there is none
M ← empty map;
for j ← 0 to n-1 do {
    if (M.get(S[j]) ≠ null) then return j;     // S[j] already seen: first repetition
    M.put(S[j], j);                             // first occurrence of S[j]: remember it
}
return -1

Trace on S=[7,3,9,3,7]S = [7, 3, 9, 3, 7]: j=0j = 0: get(7) is null, put 77; j=1j = 1: put 33; j=2j = 2: put 99; j=3j = 3: get(3) returns 11, not null, so the algorithm returns 33 (the position 44 would be the next repetition, but the algorithm has already stopped). On [4,8,15,16,23,42][4, 8, 15, 16, 23, 42] all the get return null and the result is −1-1; on [5,5][5, 5] the result is 11; on the empty sequence the loop does not run and the result is −1-1.

(b) Each iteration makes one get and (if it does not return) one put; their cost with a hash table is given in Hash TablesA hash table implements a map by sending each key through a hash function to one of N buckets, handling collisions with separate chaining, and it gives expected O(1 + load factor) time per operation but Theta(n) in the worst case.Hash Tables →.

  • Best case. If S[0]=S[1]S[0] = S[1] the algorithm returns at j=1j = 1 after a constant number of operations: Θ(1)\Theta(1).
  • Average case, distinct elements (the algorithm does all nn iterations). Under uniform hashing and with the load factor kept below a constant (by rehashing), get and put cost O(1+λ)=O(1)O(1 + \lambda) = O(1) in expectation, so the expected total is Θ(n)\Theta(n). The rehashings cost Θ(n)\Theta(n) overall, amortised over the insertions.
  • Worst case. All the keys fall in the same bucket (the table degenerates into a list). At iteration jj the chain has jj entries and the key is absent: get scans jj entries and put scans them again before appending, so the iteration costs Θ(j)\Theta(j) and the total is ∑j=0n−1Θ(j)=Θ(n2)\sum_{j=0}^{n-1} \Theta(j) = \Theta(n^2). (Running the algorithm with a constant hash function on n=10,100,400n = 10, 100, 400 distinct keys gives 90,9900,15960090, 9900, 159600 key comparisons, that is n(n−1)n(n-1).)
  • Unsorted list. Both operations are Θ(n)\Theta(n) (MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps →), so with distinct elements the cost is again Θ(n2)\Theta(n^2) in the worst case, whatever the input: the hash table is better on average, not in the worst case.

(c) Invariant: at the beginning of the iteration with index jj (0≤j≤n0 \le j \le n), (i) no position i<ji < j is a repetition, and (ii) MM contains exactly the values of S[0÷j−1]S[0 \div j-1] as keys, each associated with its position.

  • Initialisation (j=0j = 0): there are no positions <0< 0; MM is empty.
  • Maintenance: assume the invariant at j<nj < n. If S[j]S[j] is a key of MM, then by (ii) it equals some S[i]S[i] with i<ji < j, so jj is a repetition, and by (i) no smaller position is: the return j is correct. Otherwise S[j]S[j] is different from all of S[0÷j−1]S[0 \div j-1], position jj is not a repetition (so (i) holds for j+1j + 1), and the put adds exactly the new key (so (ii) holds for j+1j + 1).
  • Termination: if the loop ends normally, j=nj = n and by (i) no position is a repetition: −1-1 is correct. The loop makes nn iterations, so the algorithm terminates.

Typical mistakes: storing null as the value, which get cannot distinguish from an absent key; returning the repeated value instead of the position; returning the position of the first occurrence; claiming Θ(n)\Theta(n) in the worst case without the assumption of uniform hashing; scanning the whole sequence before answering (then the best case is no longer Θ(1)\Theta(1)).

Exercise 6 (points 10)

Programming part: this exercise is a proposal, in the style of the problems of competitive-programming sites, and is not taken from the official examples.

A sensor logs a sequence of signed integer readings. A window is a non-empty block of consecutive readings. Write in Java the method

java
static long countWindows(int[] r, long target)

that returns the number of windows of r whose readings sum to exactly target. Windows with the same readings but at different positions count as different.

Constraints. 1≤n≤2⋅1051 \le n \le 2 \cdot 10^5 where nn is r.length; −109≤r[i]≤109-10^9 \le r[i] \le 10^9; −1015≤target≤1015-10^{15} \le \text{target} \le 10^{15}.

Examples.

input output explanation
r = [1, 2, 3], target = 3 2 windows [1,2][1, 2] and [3][3]
r = [1, -1, 1, -1], target = 0 4 [1,−1][1, -1] at positions 0-1, [−1,1][-1, 1] at 1-2, [1,−1][1, -1] at 2-3 and the whole array
r = [0, 0, 0], target = 0 6 all the 3+2+13 + 2 + 1 windows

Required complexity. Expected time O(n)O(n) and O(n)O(n) extra space; the solutions that examine all the windows (Θ(n2)\Theta(n^2)) are too slow for n=2⋅105n = 2 \cdot 10^5.

Show the result

For the three examples the method returns 2, 4, 6. On r = [5]: target = 4 gives 0 and target = 5 gives 1. On an array of 200000200000 zeros with target = 0 it returns 20000100000, which does not fit in an int.

Show the full solution

Idea. Let P0=0P_0 = 0 and Pj+1=Pj+r[j]P_{j+1} = P_j + r[j] be the prefix sums. The window r[i÷j]r[i \div j] has sum Pj+1−PiP_{j+1} - P_i. So a window ending at jj has sum target exactly when an earlier prefix has value Pj+1−targetP_{j+1} - \text{target}. We scan rr once, keeping in a map (MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps →, implemented by HashMap, a hash table with separate chaining, see Hash TablesA hash table implements a map by sending each key through a hash function to one of N buckets, handling collisions with separate chaining, and it gives expected O(1 + load factor) time per operation but Theta(n) in the worst case.Hash Tables →) how many times each prefix-sum value has appeared so far; at each position we add to the answer the number of earlier prefixes equal to Pj+1−targetP_{j+1} - \text{target}. The empty prefix P0=0P_0 = 0 must be in the map from the start, otherwise the windows that begin at position 00 are missed.

java
import java.util.HashMap;
import java.util.Map;

public class Windows {

    /** Number of non-empty contiguous windows of r whose sum equals target. */
    static long countWindows(int[] r, long target) {
        Map<Long, Integer> seen = new HashMap<>();   // prefix sum -> how many prefixes have it
        seen.put(0L, 1);                             // the empty prefix, sum 0
        long prefix = 0;                             // sum of r[0..j]
        long count = 0;                              // windows found so far
        for (int x : r) {
            prefix += x;
            // windows ending here with sum target: earlier prefixes equal to prefix - target
            count += seen.getOrDefault(prefix - target, 0);
            seen.merge(prefix, 1, Integer::sum);     // record the current prefix
        }
        return count;
    }
}

The order of the two map operations matters: the lookup is done before the current prefix is recorded, so that a window is never empty (a window with target=0\text{target} = 0 would otherwise be counted from a prefix to itself).

Trace on example 2 (r = [1, -1, 1, -1], target = 0). Start: seen = {0: 1}, prefix = 0.

x prefix looked up prefix - target found count seen after
1 1 1 0 0 {0:1, 1:1}
-1 0 0 1 1 {0:2, 1:1}
1 1 1 1 2 {0:2, 1:2}
-1 0 0 2 4 {0:3, 1:2}

Result 44, as expected.

Complexity. One pass of nn iterations, each with a get and a put (getOrDefault and merge) on the hash table: expected O(1)O(1) each under uniform hashing with bounded load factor (Hash TablesA hash table implements a map by sending each key through a hash function to one of N buckets, handling collisions with separate chaining, and it gives expected O(1 + load factor) time per operation but Theta(n) in the worst case.Hash Tables →), so expected time Θ(n)\Theta(n) and Θ(n)\Theta(n) space for the at most n+1n + 1 distinct prefix sums. In the worst case, with all the prefix sums in the same bucket, the cost would be Θ(n2)\Theta(n^2), like the map implemented with a list.

Why long. The prefix sums reach 2⋅105⋅109=2⋅10142 \cdot 10^5 \cdot 10^9 = 2 \cdot 10^{14} and the number of windows reaches n(n+1)/2=20000100000n(n+1)/2 = 20000100000 for n=200000n = 200000: both overflow int. Typical mistakes: int for the prefix sum or for the counter; forgetting seen.put(0L, 1); recording the current prefix before looking up prefix - target; using a double loop (correct but Θ(n2)\Theta(n^2), about 2⋅10102 \cdot 10^{10} steps).

Test battery (compiled with JDK 21 and -Xlint:all, no warnings, and run):

  • the three examples: 2, 4, 6; also [5] with targets 44 and 55: 0, 1;
  • 2000020000 random arrays of length 11-3030 with values in [−3,3][-3, 3] and targets in [−4,4][-4, 4], compared with the brute-force double loop: 00 mismatches;
  • 200000200000 zeros, target = 0: 20000100000;
  • 200000200000 random readings in [−109,109][-10^9, 10^9], target = 7: 0 windows (the whole run on the three large inputs takes about 8080 ms);
  • 200000200000 readings equal to 10910^9 and target =2⋅1014= 2 \cdot 10^{14}: 1 (only the whole array).
Self-assessment grid
Exercise Points What must be there for full marks Typical mistakes
1 3 The classes {f1,f7}≺{f2}≺{f4}≺{f3}≺{f5}≺{f6}\{f_1, f_7\} \prec \{f_2\} \prec \{f_4\} \prec \{f_3\} \prec \{f_5\} \prec \{f_6\} with the reason of each step; both bounds 7n≤f4≤107n7n \le f_4 \le 107n with n0=1n_0 = 1 Treating ln⁡\ln and log⁡2\log_2 as different classes; taking 2n/102^{n/10} as polynomial; proving only O(n)O(n)
2 4 Trace with result 33 and 88 tests; best case Θ(1)\Theta(1) with an instance; worst case Θ(n)\Theta(n) with upper bound (geometric series) and lower bound (one instance) and the error in the nlog⁡nn \log n claim Answering Θ(nlog⁡n)\Theta(n \log n); not distinguishing best and worst case; best case Θ(n)\Theta(n)
3 4 The hash values; tables after the 4th put, after the rehash (order of reinsertion, N=11N = 11) and at the end; λ=8/11\lambda = 8/11; 22 and 2828 comparisons; ninth put triggers the rehash to 2323 and pp must change Wrong reinsertion order; N=10N = 10 instead of the prime 1111; forgetting p>Np > N; counting rehash reinsertions as comparisons
4 5 Tree and visible nodes; recursive algorithm with explicit base case and best passed down; 2n+12n + 1 calls, Θ(n)\Theta(n) independent of MM; MM up to exponential in nn Cost Θ(M)\Theta(M); missing null test; wrong update of best; ≥\ge instead of >>
5 6 One pass with get/put, return j on the first key already in MM, the position stored as value; best Θ(1)\Theta(1), average Θ(n)\Theta(n), worst Θ(n2)\Theta(n^2), list-based Θ(n2)\Theta(n^2); invariant with the three steps Value null stored; returning the value or the first occurrence; no assumption on the hash function; invariant without initialisation or maintenance
6 10 Prefix sums plus a map of counts with the empty prefix in it; lookup before insertion; long everywhere; expected O(n)O(n); tested on the examples and on large inputs int overflow; missing initial {0: 1}; wrong order of lookup and insertion; Θ(n2)\Theta(n^2) double loop