Count Subtrees With Max Distance Between Cities Problem
Description
LeetCode Problem 1617.
There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [u_i, v_i] represents a bidirectional edge between cities u_i and v_i. There exists a unique path between each pair of cities. In other words, the cities form a tree.
A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.
For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d.
Return an array of size n-1 where the d^th element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d.
Notice that the distance between the two cities is the number of edges in the path between them.
Example 1:

Input: n = 4, edges = [[1,2],[2,3],[2,4]]
Output: [3,4,0]
Explanation:
The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.
The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.
No subtree has two nodes where the max distance between them is 3.
Example 2:
Input: n = 2, edges = [[1,2]]
Output: [1]
Example 3:
Input: n = 3, edges = [[1,2],[2,3]]
Output: [2,1]
Constraints:
2 <= n <= 15edges.length == n-1edges[i].length == 21 <= u_i, v_i <= n- All pairs
(u_i, v_i)are distinct.
Solution
Approach: Enumerate Subsets, Then BFS Twice
With n <= 15 there are at most 215 = 32768 subsets of cities, so we can try every one of them as a bitmask.
For each mask with at least two cities:
- Is it a subtree? Run a BFS from any city in the mask, walking only to neighbours that are also in the mask. The subset is a subtree exactly when this BFS reaches every city of the mask; otherwise the cities are not connected through the subset alone and we skip it.
- What is its maximum distance? The maximum distance between two cities of a tree is its diameter, and the classic way to find it is two searches: the city farthest from any start is one end of a diameter, and the distance from that city to the farthest city from it is the diameter. The first BFS above already gives us the farthest city, so we only need one more BFS from there.
Add one to ans[d - 1] for the diameter d. Masks with a single bit are skipped, since a single city has no pair.
The two-BFS trick works only on trees; that is fine here because a connected subset of a tree is itself a tree.
Complexity: O(2n · n) time, since each mask runs two BFS over at most n cities, and O(n) extra space.
from collections import deque
class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
g = [[] for _ in range(n)]
for u, v in edges:
g[u - 1].append(v - 1)
g[v - 1].append(u - 1)
def bfs(start: int, mask: int):
"""BFS inside mask: returns (farthest city, its distance, cities reached as a mask)."""
dist = {start: 0}
q = deque([start])
far = start
seen = 1 << start
while q:
u = q.popleft()
if dist[u] > dist[far]:
far = u
for v in g[u]:
if mask >> v & 1 and not seen >> v & 1:
seen |= 1 << v
dist[v] = dist[u] + 1
q.append(v)
return far, dist[far], seen
ans = [0] * (n - 1)
for mask in range(1, 1 << n):
if mask & (mask - 1) == 0:
continue # a single city has no pair of cities
start = mask.bit_length() - 1
far, _, seen = bfs(start, mask)
if seen != mask:
continue # not connected, so not a subtree
_, diameter, _ = bfs(far, mask)
ans[diameter - 1] += 1
return ans