Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with None for gaps.
Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with None for gaps.
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 good(nd, mx):
if not nd: return 0
g = 1 if nd.v >= mx else 0
m = max(mx, nd.v)
return g + good(nd.l, m) + good(nd.r, m)
print(good(build([5, 3, 8, 6, 1, None, 9, None, 7]), float('-inf')))What is printed?- A. 4
- B. 5
- C. 6
- D. 3
Correct answer: B. 5
Tree: 5 → (3, 8); 3 → (6, 1); 8 → (−, 9); 6 → (−, 7). Good nodes: 5, 8, 6 (path max 5), 9 and 7 (path max 6), i.e. 5. 3 and 1 are below the root value 5.
More Coding Interview Problems questions
- Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be…
- Problem: Count islands in a grid of 1s (land) and 0s where land cells touching even DIAGONALLY belong to the same island. python g =…
- Problem: In an unweighted graph, find the shortest distance from node 0 to node 5 and the NUMBER of distinct shortest paths. python from…
- A Floyd–Warshall implementation writes its loops as for i … for j … for k (k innermost) instead of k outermost, and runs the triple loop…
- Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight. python edges =…
- Problem: A CPU runs tasks (letters); identical tasks need at least n idle-or-other slots between them. Find the minimum total time slots…