#2581
Count Number of Possible Root Nodes
HardArrayHash TableDynamic ProgrammingTreeDepth-First SearchHash MapDFS
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)
In the optimal approach, we can utilize a DFS to calculate correct guesses while traversing the tree. This allows us to efficiently determine how many guesses are correct for each node without re-evaluating all guesses from scratch.
⚙️
Algorithm
4 steps- 1Step 1: Build the graph from the edges.
- 2Step 2: Count the correct guesses for an arbitrary root (say node 0).
- 3Step 3: Use DFS to traverse the tree and adjust the count of correct guesses for each child node based on the parent node's count.
- 4Step 4: If the count of correct guesses for a node is at least k, increment the possible root count.
solution.py27 lines
1def count_possible_roots(edges, guesses, k):
2 from collections import defaultdict
3 graph = defaultdict(list)
4 for u, v in edges:
5 graph[u].append(v)
6 graph[v].append(u)
7 guess_map = {(u, v): 1 for u, v in guesses}
8 correct_count = 0
9 correct_guesses = [0] * len(edges)
10
11 def dfs(node, parent):
12 nonlocal correct_count
13 current_count = 0
14 for neighbor in graph[node]:
15 if neighbor == parent:
16 continue
17 current_count += dfs(neighbor, node)
18 if parent in graph[node]:
19 if (parent, node) in guess_map:
20 current_count += 1
21 correct_guesses[node] = current_count
22 if current_count >= k:
23 correct_count += 1
24 return current_count
25
26 dfs(0, -1)
27 return correct_countℹ
Complexity note: The time complexity is O(n) because we traverse each node once in the DFS. The space complexity is O(n) due to the storage of the graph and the guess set.
- 1Understanding the structure of trees is crucial for solving problems related to them.
- 2Using DFS allows for efficient counting and adjustment of guesses without redundant checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.