Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Return the (1-based) level of a binary tree with the largest sum of values (smallest level on ties).
Problem: Return the (1-based) level of a binary tree with the largest sum of values (smallest level on ties).
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]
from collections import deque
def best_level(root):
q, lvl, best, ans = deque([root]), 0, float('-inf'), 0
while q:
lvl += 1; s = 0
for _ in range(len(q)):
n = q.popleft(); s += n.v
if n.l: q.append(n.l)
if n.r: q.append(n.r)
if s > best: best, ans = s, lvl
return ans
print(best_level(build([1, 7, 0, 7, -8, None, None, -9, 20])))What is printed?- A. 2
- B. 3
- C. 4
- D. 1
Correct answer: C. 4
Level sums: 1, 7 + 0 = 7, 7 − 8 = −1, −9 + 20 = 11. The deepest level wins with 11; using >= instead of > would only matter for ties.
More Coding Interview Problems questions
- 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…
- Problem: Split an array into contiguous parts of length at most k; every element of a part becomes that part's maximum. Maximise the final…