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)
  1. A. 13 15 33 True
  2. B. 11 15 31 True
  3. C. 16 16 32 False
  4. 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.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic