Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
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: Insert keys into an AVL tree (rebalancing with rotations) and print the root and the tree height (a single node has height 1).
class T:
def __init__(s, v): s.v, s.l, s.r, s.h = v, None, None, 1
def h(n): return n.h if n else 0
def fix(n): n.h = 1 + max(h(n.l), h(n.r)); return n
def rot_r(y): x = y.l; y.l = x.r; x.r = y; fix(y); return fix(x)
def rot_l(x): y = x.r; x.r = y.l; y.l = x; fix(x); return fix(y)
def ins(n, v):
if not n: return T(v)
if v < n.v: n.l = ins(n.l, v)
else: n.r = ins(n.r, v)
fix(n); b = h(n.l) - h(n.r)
if b > 1 and v < n.l.v: return rot_r(n)
if b < -1 and v >= n.r.v: return rot_l(n)
if b > 1: n.l = rot_l(n.l); return rot_r(n)
if b < -1: n.r = rot_r(n.r); return rot_l(n)
return n
root = None
for v in [10, 20, 30, 40, 50, 25]: root = ins(root, v)
print(root.v, root.h)What is printed?- A. 20 3
- B. 30 3
- C. 40 3
- D. 10 6
Correct answer: B. 30 3
10, 20, 30 trigger a left rotation (root 20); 40, 50 rotate 30–40–50 into 40 with children 30, 50. Inserting 25 (under 30) makes the root's right subtree height 3 against a left height of 1, a right-left case, so a double rotation makes 30 the root (children 20 and 40) with height 3.
More Coding Interview Problems questions
- 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?
- A hash table with separate chaining and simple uniform hashing has n keys in m buckets (load factor α = n/m). What is the expected time of…
- An LRU cache must support get and put in O(1). Which design achieves this?