There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. 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 sizen-1where the dthelement (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.
Problem summary: There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. 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 dth 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
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Bit Manipulation · Tree
Example 1
4
[[1,2],[2,3],[2,4]]
Example 2
2
[[1,2]]
Example 3
3
[[1,2],[2,3]]
Related Problems
Tree Diameter (tree-diameter)
Step 02
Core Insight
What unlocks the optimal approach
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)?
To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask.
The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1617: Count Subtrees With Max Distance Between Cities
class Solution {
private List<Integer>[] g;
private int msk;
private int nxt;
private int mx;
public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (int[] e : edges) {
int u = e[0] - 1, v = e[1] - 1;
g[u].add(v);
g[v].add(u);
}
int[] ans = new int[n - 1];
for (int mask = 1; mask < 1 << n; ++mask) {
if ((mask & (mask - 1)) == 0) {
continue;
}
msk = mask;
mx = 0;
int cur = 31 - Integer.numberOfLeadingZeros(msk);
dfs(cur, 0);
if (msk == 0) {
msk = mask;
mx = 0;
dfs(nxt, 0);
++ans[mx - 1];
}
}
return ans;
}
private void dfs(int u, int d) {
msk ^= 1 << u;
if (mx < d) {
mx = d;
nxt = u;
}
for (int v : g[u]) {
if ((msk >> v & 1) == 1) {
dfs(v, d + 1);
}
}
}
}
// Accepted solution for LeetCode #1617: Count Subtrees With Max Distance Between Cities
func countSubgraphsForEachDiameter(n int, edges [][]int) []int {
g := make([][]int, n)
for _, e := range edges {
u, v := e[0]-1, e[1]-1
g[u] = append(g[u], v)
g[v] = append(g[v], u)
}
ans := make([]int, n-1)
var msk, nxt, mx int
var dfs func(int, int)
dfs = func(u, d int) {
msk ^= 1 << u
if mx < d {
mx, nxt = d, u
}
for _, v := range g[u] {
if msk>>v&1 == 1 {
dfs(v, d+1)
}
}
}
for mask := 1; mask < 1<<n; mask++ {
if mask&(mask-1) == 0 {
continue
}
msk, mx = mask, 0
cur := bits.Len(uint(msk)) - 1
dfs(cur, 0)
if msk == 0 {
msk, mx = mask, 0
dfs(nxt, 0)
ans[mx-1]++
}
}
return ans
}
# Accepted solution for LeetCode #1617: Count Subtrees With Max Distance Between Cities
class Solution:
def countSubgraphsForEachDiameter(
self, n: int, edges: List[List[int]]
) -> List[int]:
def dfs(u: int, d: int = 0):
nonlocal mx, nxt, msk
if mx < d:
mx, nxt = d, u
msk ^= 1 << u
for v in g[u]:
if msk >> v & 1:
dfs(v, d + 1)
g = defaultdict(list)
for u, v in edges:
u, v = u - 1, v - 1
g[u].append(v)
g[v].append(u)
ans = [0] * (n - 1)
nxt = mx = 0
for mask in range(1, 1 << n):
if mask & (mask - 1) == 0:
continue
msk, mx = mask, 0
cur = msk.bit_length() - 1
dfs(cur)
if msk == 0:
msk, mx = mask, 0
dfs(nxt)
ans[mx - 1] += 1
return ans
// Accepted solution for LeetCode #1617: Count Subtrees With Max Distance Between Cities
struct Solution;
impl Solution {
fn count_subgraphs_for_each_diameter(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> {
let n = n as usize;
let mut adj = vec![vec![]; n];
for edge in &edges {
let u = edge[0] as usize - 1;
let v = edge[1] as usize - 1;
adj[u].push(v);
adj[v].push(u);
}
let mut res = vec![0; n - 1];
let full: u32 = (1 << n) as u32 - 1;
for mask in 1..=full {
let node_count = mask.count_ones() as usize;
let mut edge_count = 0;
for edge in &edges {
let u = edge[0] as usize - 1;
let v = edge[1] as usize - 1;
if (mask & 1 << u) != 0 && (mask & 1 << v) != 0 {
edge_count += 1;
}
}
if node_count == 1 || node_count != edge_count + 1 {
continue;
}
let mut u = 0;
for i in 0..n {
if (mask & 1 << i) != 0 {
u = i;
break;
}
}
let mut max = 0;
let mut mask = mask;
Self::dfs(u, &mut mask, &mut max, &adj, n);
res[max - 1] += 1;
}
res
}
fn dfs(u: usize, mask: &mut u32, max: &mut usize, adj: &[Vec<usize>], n: usize) -> usize {
*mask ^= 1 << u;
let mut max_dia = 0;
for &v in &adj[u] {
if (*mask & 1 << v) != 0 {
let dia = Self::dfs(v, mask, max, adj, n);
*max = (*max).max(max_dia + dia);
max_dia = max_dia.max(dia);
}
}
max_dia + 1
}
}
#[test]
fn test() {
let n = 4;
let edges = vec_vec_i32![[1, 2], [2, 3], [2, 4]];
let res = vec![3, 4, 0];
assert_eq!(Solution::count_subgraphs_for_each_diameter(n, edges), res);
let n = 2;
let edges = vec_vec_i32![[1, 2]];
let res = vec![1];
assert_eq!(Solution::count_subgraphs_for_each_diameter(n, edges), res);
let n = 3;
let edges = vec_vec_i32![[1, 2], [2, 3]];
let res = vec![2, 1];
assert_eq!(Solution::count_subgraphs_for_each_diameter(n, edges), res);
}
// Accepted solution for LeetCode #1617: Count Subtrees With Max Distance Between Cities
function countSubgraphsForEachDiameter(n: number, edges: number[][]): number[] {
const g = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
g[u - 1].push(v - 1);
g[v - 1].push(u - 1);
}
const ans: number[] = new Array(n - 1).fill(0);
let [mx, msk, nxt] = [0, 0, 0];
const dfs = (u: number, d: number) => {
if (mx < d) {
mx = d;
nxt = u;
}
msk ^= 1 << u;
for (const v of g[u]) {
if ((msk >> v) & 1) {
dfs(v, d + 1);
}
}
};
for (let mask = 1; mask < 1 << n; ++mask) {
if ((mask & (mask - 1)) === 0) {
continue;
}
msk = mask;
mx = 0;
const cur = 31 - numberOfLeadingZeros(msk);
dfs(cur, 0);
if (msk === 0) {
msk = mask;
mx = 0;
dfs(nxt, 0);
++ans[mx - 1];
}
}
return ans;
}
function numberOfLeadingZeros(i: number): number {
if (i == 0) return 32;
let n = 1;
if (i >>> 16 == 0) {
n += 16;
i <<= 16;
}
if (i >>> 24 == 0) {
n += 8;
i <<= 8;
}
if (i >>> 28 == 0) {
n += 4;
i <<= 4;
}
if (i >>> 30 == 0) {
n += 2;
i <<= 2;
}
n -= i >>> 31;
return n;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.