Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count the BST keys within [lo, hi], pruning subtrees that cannot contain answers.

Problem: Count the BST keys within [lo, hi], pruning subtrees that cannot contain answers.
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def ins(r, v):
    if not r: return T(v)
    if v < r.v: r.l = ins(r.l, v)
    else: r.r = ins(r.r, v)
    return r
root = None
for v in [20, 10, 30, 5, 15, 25, 35, 12, 17, 27]: root = ins(root, v)
visits = 0
def cnt(n, lo, hi):
    global visits
    if not n: return 0
    visits += 1
    if n.v < lo: return cnt(n.r, lo, hi)
    if n.v > hi: return cnt(n.l, lo, hi)
    return 1 + cnt(n.l, lo, hi) + cnt(n.r, lo, hi)
print(cnt(root, 13, 26), visits)
What is printed?
  1. A. 5 10
  2. B. 4 10
  3. C. 4 8
  4. D. 5 7

Correct answer: C. 4 8

Keys in [13, 26]: 15, 17, 20, 25 → 4. Since 10 < 13 only its right subtree is searched (5 is never visited), and since 30 > 26 only its left subtree is (35 is skipped): 8 of the 10 nodes are visited.

More Coding Interview Problems questions

Exams that ask this topic