Data Structures & AlgorithmsModerateProduct Company SDE · tree round

Problem: What is the diameter (in edges) of the tree with edges 1-2, 2-3, 2-4, 4-5, 5-6? Use the double BFS code.

Problem: What is the diameter (in edges) of the tree with edges 1-2, 2-3, 2-4, 4-5, 5-6? Use the double BFS code.
from collections import deque
def far(g, 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=lambda k: d[k])
    return x, d[x]
g = {i: [] for i in range(1, 7)}
for u, v in [(1, 2), (2, 3), (2, 4), (4, 5), (5, 6)]:
    g[u].append(v)
    g[v].append(u)
x, _ = far(g, 1)
print(far(g, x)[1])
What is printed?
  1. A. 3
  2. B. 5
  3. C. 6
  4. D. 4

Correct answer: D. 4

The farthest vertex from 1 is 6 (distance 4), and the farthest from 6 is 1 or 3 at distance 4. The double BFS works on any tree because the first sweep ends at a diameter endpoint.

More Coding Interview Problems questions

Exams that ask this topic