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?- A. 3
- B. 5
- C. 6
- 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
- Problem: A robot starts at (0, 0) facing north (+y). Commands: F moves one step forward, B one step backward (facing unchanged), L turns…
- Problem: What is the KMP prefix-function array pi for the string 'ababaca'? python s = 'ababaca' pi = [0] len(s) for i in range(1…
- Problem: What is the lexicographically smallest rotation of 'bcabca'? python s = 'bcabca' print(min(s[i:] + s[:i] for i in range(len(s))))…
- Problem: Items (weight, value) are (2,3), (3,4), (4,5), and each may be used at most once. Capacity W = 7. Run the code below to find the…
- Problem: How many ways can a staircase of 8 steps be climbed if each move climbs 1, 3 or 4 steps? Run the DP below. python ways = [0] 9…
- Problem: Jobs are given as (deadline, profit): (2,100), (1,19), (2,27), (1,25), (3,15). Each job takes one unit slot and must finish by…