Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree.
Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree.
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
nodes = [T(x) if x is not None else None for x in xs]
kids = iter(nodes[1:])
for nd in nodes:
if nd:
nd.l = next(kids, None); nd.r = next(kids, None)
return nodes[0]
def best(nd, lo, hi):
if not nd: return hi - lo
lo, hi = min(lo, nd.v), max(hi, nd.v)
return max(best(nd.l, lo, hi), best(nd.r, lo, hi))
root = build([8, 3, 10, 1, 6, None, 14, None, None, 4, 7, 13])
print(best(root, root.v, root.v))What is printed?- A. 7
- B. 13
- C. 11
- D. 6
Correct answer: A. 7
Carry the min and max along each root-to-leaf path; the answer is the largest max − min. On the path 8 → 3 → 1 the spread is 8 − 1 = 7; on 8 → 10 → 14 → 13 it is 14 − 8 = 6. The best is 7. 13 = 14 − 1 pairs nodes on different branches, which are not ancestor-related.
More Coding Interview Problems questions
- Problem: Return the (1-based) level of a binary tree with the largest sum of values (smallest level on ties). python class T: def init(s…
- Problem: Every minute, fresh oranges (1) next to rotten ones (2) rot (4 directions). How many minutes until no fresh orange remains (−1 if…
- Problem: Find the path from node 0 to node 3 with the maximum product of edge success probabilities (Dijkstra on −log p, or a max-heap on…
- Problem: Each bus route is a loop of stops. Find the fewest buses needed to travel from stop S to stop T (BFS over routes, not stops)…
- Problem: Hire exactly K workers; each is paid in proportion to quality, and at least their minimum wage. Minimise total pay (sort by…
- Problem: In a sorted array every value appears twice except one. Find it in O(log n) using index parity. python def single(a): lo, hi = 0…