Data Structures & AlgorithmsHardTCS NQT · Infosys pattern
What is printed? (diameter of an unweighted tree with two BFS passes)
What is printed? (diameter of an unweighted tree with two BFS passes)
from collections import deque
edges = [(1, 2), (1, 3), (2, 4), (2, 5), (5, 6), (3, 7), (7, 8), (8, 9)]
g = {}
for u, v in edges: g.setdefault(u, []).append(v); g.setdefault(v, []).append(u)
def far(s):
d = {s: 0}; q = deque([s])
while q:
u = q.popleft()
for v in g[u]:
if v not in d: d[v] = d[u] + 1; q.append(v)
x = max(d, key=d.get); return x, d[x]
a, _ = far(1); b2, dia = far(a)
print(a, dia)- A. 9 6
- B. 6 7
- C. 9 8
- D. 9 7
Correct answer: D. 9 7
BFS from any node reaches one end of a diameter (from 1 the farthest node is 9, at depth 4); a second BFS from 9 finds the other end, 6: 9 → 8 → 7 → 3 → 1 → 2 → 5 → 6 = 7 edges. The two-pass trick works for trees (not general graphs). O(n).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (articulation points by brute force removal) python edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (5…
- What is printed? (strongly connected components count, Kosaraju) python g = {0: [1], 1: [2], 2: [0, 3], 3: [4], 4: [5], 5: [3], 6: [5, 7]…
- What is printed? (greedy fractional knapsack) python items = [(10, 60), (20, 100), (30, 120)] # (weight, value) cap, total = 50, 0.0 for…
- What is printed? (minimum platforms / overlapping intervals with a heap) python import heapq iv = sorted([(1, 4), (2, 3), (3, 6), (5, 7)…
- A complete binary tree is stored in an array with the root at index 1. A node at index 37 – what are its parent, left child and right…
- What is printed? (Catalan-style recursion with memo: number of ways to fully parenthesise a product of n matrices) python from functools…