Data Structures & AlgorithmsVery hardProduct company OA
Problem: Return all node values at exactly distance k from a target node (distance counts edges, moving up or down). Record parent pointers, then BFS from the target. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
Problem: Return all node values at exactly distance k from a target node (distance counts edges, moving up or down). Record parent pointers, then BFS from the target. 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 dist_k(root, target, k):
parent = {}; q = deque([root]); start = None
while q:
n = q.popleft()
if n.v == target: start = n
for c in (n.l, n.r):
if c: parent[c] = n; q.append(c)
seen = {start}; frontier = [start]
for _ in range(k):
nxt = []
for n in frontier:
for m in (n.l, n.r, parent.get(n)):
if m and m not in seen: seen.add(m); nxt.append(m)
frontier = nxt
return sorted(n.v for n in frontier)
print(dist_k(build([1, 2, 3, 4, 5, None, 6, None, None, 7, 8]), 5, 2))What is printed?- A. [4]
- B. [1, 4]
- C. [1, 3, 4]
- D. [1, 4, 7, 8]
Correct answer: B. [1, 4]
Turning the tree into an undirected graph (children + parent) makes this a plain BFS. Tree: 1 → (2, 3), 2 → (4, 5), 3 → (–, 6), 5 → (7, 8). From 5: distance 1 = {2, 7, 8}; distance 2 = {1, 4} (7 and 8 are leaves). Searching only downwards would find nothing at depth 2; 3 is at distance 3. O(n).
More Coding Interview Problems questions
- Problem: Rocks are smashed repeatedly: take the two heaviest; if equal both vanish, otherwise the difference remains. Report the last…
- Problem: Room 0 is open; each room holds keys to other rooms. Can every room be visited? (DFS over keys.) python def canvisitall(rooms)…
- Problem: Traverse a small directed graph (adjacency lists in the order shown) from node 0, once with recursive DFS and once with BFS…
- Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped. python import…
- Problem: Each element of a log is at most k = 2 positions away from its sorted position. Sort it with a min-heap of size k + 1. python…
- Problem: Is an undirected graph with n nodes a tree? Check edge count = n − 1 and that union-find never sees an edge inside one component…