Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
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 child +1). BFS guarantees the shallowest node per column. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
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 child +1). BFS guarantees the shallowest node per column. 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 top_view(root):
first = {}; q = deque([(root, 0)])
while q:
n, c = q.popleft()
if c not in first: first[c] = n.v
if n.l: q.append((n.l, c - 1))
if n.r: q.append((n.r, c + 1))
return [first[c] for c in sorted(first)]
print(top_view(build([1, 2, 3, None, 4, 5, 6, None, 8, 7])))What is printed?- A. [2, 1, 3, 6]
- B. [2, 1, 8, 6]
- C. [7, 2, 1, 3, 6]
- D. [2, 4, 1, 3, 6]
Correct answer: A. [2, 1, 3, 6]
Columns: 1 (0), 2 (−1), 3 (+1), 4 (0), 5 (0), 6 (+2), 8 (+1), 7 (−1). BFS reaches each column's shallowest node first: −1 → 2, 0 → 1, +1 → 3, +2 → 6. A preorder DFS that keeps the first node visited reaches 8 (depth 3, via 2 → 4 → 8) before 3 (depth 1) and wrongly reports 8 for column +1. O(n log n) with the final sort.
More Coding Interview Problems questions
- 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…
- Problem: Place the minimum number of cameras on tree nodes so every node is monitored (a camera covers itself, its parent and its…