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?- A. 5 10
- B. 4 10
- C. 4 8
- 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
- Problem: Delete a node with two children from a BST by replacing it with its inorder successor; print the preorder afterwards. python…
- Problem: Insert keys into an AVL tree (rebalancing with rotations) and print the root and the tree height (a single node has height 1)…
- Problem: Ackermann's function grows faster than any primitive-recursive function. Compute A(2, 3) and count the recursive calls. python…
- Problem: Count the calls made by naive recursive Fibonacci versus a memoised version for n = 10. python from functools import lrucache…
- What is the time complexity of this loop? python for i in range(1, n + 1): j = 1 while j j <= i: j += 1
- What is the solution of T(n) = 2T(√n) + log n?