#1617
Count Subtrees With Max Distance Between Cities
HardDynamic ProgrammingBit ManipulationTreeEnumerationBitmaskDepth-First SearchDynamic ProgrammingGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use a more efficient approach by leveraging the properties of trees. By using dynamic programming and depth-first search, we can compute the maximum distances in a single traversal.
⚙️
Algorithm
3 steps- 1Step 1: Build the adjacency list from the edges.
- 2Step 2: Use DFS to calculate the maximum distance for each subtree rooted at each node.
- 3Step 3: Maintain a count of subtrees for each maximum distance found during the DFS.
solution.py28 lines
1# Full working Python code
2from collections import defaultdict
3
4def countSubtrees(n, edges):
5 graph = defaultdict(list)
6 for u, v in edges:
7 graph[u].append(v)
8 graph[v].append(u)
9
10 result = [0] * (n - 1)
11 dp = [0] * (n + 1)
12
13 def dfs(node, parent):
14 max_dist = 0
15 for neighbor in graph[node]:
16 if neighbor == parent:
17 continue
18 child_dist = dfs(neighbor, node) + 1
19 result[child_dist - 1] += 1
20 max_dist = max(max_dist, child_dist)
21 return max_dist
22
23 for i in range(1, n + 1):
24 if dp[i] == 0:
25 dfs(i, -1)
26
27 return result
28ℹ
Complexity note: The time complexity is O(n) because we traverse each node once during the DFS. The space complexity is O(n) due to the graph representation and the recursion stack.
- 1Understanding tree properties can significantly reduce complexity.
- 2Dynamic programming can optimize recursive solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.