Data Structures & AlgorithmsHardProduct company OA
Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs): # level order, None = missing child
root = T(xs[0]); q = deque([root]); i = 1
while i < len(xs):
node = q.popleft()
for side in ("l", "r"):
if i < len(xs) and xs[i] is not None:
setattr(node, side, T(xs[i])); q.append(getattr(node, side))
i += 1
return root
def good(t, mx=float("-inf")):
if not t: return 0
return (t.v >= mx) + good(t.l, max(mx, t.v)) + good(t.r, max(mx, t.v))
print(good(build([4, 2, 6, 5, 1, 4, 8, None, None, 7])))What is printed?- A. 3
- B. 5
- C. 4
- D. 6
Correct answer: B. 5
Pass the path maximum down. Tree: 4 → (2, 6); 2 → (5, 1); 6 → (4, 8); 1 → (7, –). Good: 4, 6, 5 (path max 4), 8, 7 (path 4, 2, 1, 7). Not good: 2, 1 and the lower 4 (below 6). Equal values count as good (≥). O(n).
More Coding Interview Problems questions
- Problem: Exactly two keys of a BST were swapped by mistake. Find them with an inorder traversal: the first key is the left side of the…
- Problem: Trim a BST so that only keys in [lo, hi] remain (keeping BST structure), then print its preorder. Trees are built from a…
- Problem: Rebuild a BST from its preorder in O(n) using an upper bound per recursive call, then print its postorder and height (nodes on…
- Problem: Print the top view of a tree (the first node seen in each vertical column, left to right; root column 0, left child −1, right…
- Problem: Return the k-th permutation (1-based, lexicographic) of 1..n directly using the factorial number system. python from math import…
- Problem: Count permutations p of 1..n where for every position i (1-based) p[i] is divisible by i or i is divisible by p[i] (backtracking…