Data Structures & AlgorithmsHardProduct company OA
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 the longest path).
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 the longest path).
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def from_pre(p):
i = 0
def go(hi):
nonlocal i
if i == len(p) or p[i] > hi: return None
node = T(p[i]); i += 1
node.l = go(node.v); node.r = go(hi)
return node
return go(float("inf"))
def post(t): return post(t.l) + post(t.r) + [t.v] if t else []
def height(t): return 1 + max(height(t.l), height(t.r)) if t else 0
r = from_pre([9, 4, 2, 6, 5, 13, 11, 15])
print(post(r), height(r))What is printed?- A. [5, 2, 6, 4, 11, 15, 13, 9] 4
- B. [2, 5, 6, 4, 11, 15, 13, 9] 3
- C. [2, 4, 5, 6, 9, 11, 13, 15] 4
- D. [2, 5, 6, 4, 11, 15, 13, 9] 4
Correct answer: D. [2, 5, 6, 4, 11, 15, 13, 9] 4
Each value is consumed once: a subtree accepts keys below its bound, the left child gets bound = node value, the right child inherits the parent bound. Tree: 9 → (4, 13); 4 → (2, 6); 6 → (5, –); 13 → (11, 15). Postorder 2, 5, 6, 4, 11, 15, 13, 9; longest path 9-4-6-5 has 4 nodes. Inserting keys one by one would also work but costs O(n²) on skewed input.
More Coding Interview Problems questions
- 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…
- Problem: Can all matchsticks form a square (every stick used exactly once)? Backtrack placing sticks (longest first) into 4 sides…
- Problem: Insert '+', '−' or '' between the digits (or leave digits joined) so the expression equals the target. Operands may not have…
- Problem: A thief robs houses arranged as a binary tree; robbing two directly linked houses triggers an alarm. Each node returns (best if…