Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Return (level, sum) of the level with the largest sum, levels numbered from 1 (smallest level on ties). Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
Problem: Return (level, sum) of the level with the largest sum, levels numbered from 1 (smallest level on ties). 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 best_level(root):
q = deque([root]); lvl = best_lvl = 1; best = float("-inf")
while q:
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, best_lvl = s, lvl
lvl += 1
return best_lvl, best
print(best_level(build([2, -6, 1, 9, 4, None, -3, 5])))What is printed?- A. (3, 10)
- B. (4, 5)
- C. (1, 2)
- D. (3, 13)
Correct answer: A. (3, 10)
BFS one level at a time (the inner loop runs len(q) times). Level sums: 2; −6 + 1 = −5; 9 + 4 − 3 = 10; 5 → level 3. The strict '>' keeps the earliest level on ties. Forgetting the −3 gives 13. O(n).
More Coding Interview Problems questions
- Problem: Each root-to-leaf path spells a number (digits from root to leaf). Return the sum of these numbers. Trees are built from a…
- Problem: Split a string into pieces that are all palindromes and list every such partition (backtracking). python def palparts(s): res =…
- Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing…
- Problem: Restore all valid IPv4 addresses from a digit string (four parts, each 0–255, no leading zeros except "0"). python def…
- Problem: Return every value an arithmetic expression can take under all possible full parenthesisations (divide and conquer on each…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a…