Data Structures & AlgorithmsVery hardProduct company OA
Recursive segment tree with children 2·node and 2·node + 1: the largest array index actually used for a given n. What is printed?
Recursive segment tree with children 2·node and 2·node + 1: the largest array index actually used for a given n. What is printed?
def max_index(n):
best = 0
def build(node, l, r):
nonlocal best
best = max(best, node)
if l == r: return
m = (l + r) // 2
build(2 * node, l, m); build(2 * node + 1, m + 1, r)
build(1, 0, n - 1)
return best
print(max_index(6), max_index(8), max_index(17), max(max_index(n) / n for n in range(1, 2000)) < 4)- A. 13 15 33 True
- B. 11 15 31 True
- C. 16 16 32 False
- D. 13 16 34 True
Correct answer: A. 13 15 33 True
The heap-numbered tree is not complete when n is not a power of two, so indices go past 2n − 1: for n = 6 the deepest node is 13, for n = 8 (power of two) exactly 2n − 1 = 15, for n = 17 the long left branch reaches 33 > 2n. The bound 2·2^⌈log₂ n⌉ < 4n is why '4n' is the safe array size; '2n' overflows for n = 6 and 17. An iterative bottom-up tree with size 2n avoids the issue.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Match each recurrence to its tight bound: (P) T(n) = 2T(n/2) + n log n (Q) T(n) = 2T(n/2) + n / log n (R) T(n) = T(n/2) + log n (S) T(n) =…
- A road network has n ≤ 2·10⁵ junctions and m ≤ 2·10⁵ roads; each road is either free (0) or tolled (1). You need the minimum number of…
- Which loop nests perform Θ(n log n) executions of work()? c / A / for (i = 1; i <= n; i++) for (j = i; j <= n; j += i) work(); / B / for…
- A full binary tree (every node has 0 or 2 children) has 10 internal nodes. How many leaves does it have?
- An undirected graph with V vertices and E edges is stored as adjacency lists. How many entries do all the lists hold in total?
- Which traversal should be used to free every node of a binary tree, so that no node is freed before its children?