#2867
Count Valid Paths in a Tree
HardMathDynamic ProgrammingTreeDepth-First SearchNumber TheoryDepth-First SearchSieve of EratosthenesTree 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 single DFS traversal to count valid paths by maintaining a count of prime nodes along the way. This approach is efficient as it avoids redundant calculations and leverages the tree structure.
⚙️
Algorithm
3 steps- 1Step 1: Use the Sieve of Eratosthenes to identify all prime numbers up to n.
- 2Step 2: Perform a DFS from each node, keeping track of the count of prime nodes encountered on the path.
- 3Step 3: For each node, count how many valid paths can be formed with the prime count being exactly one.
solution.py31 lines
1def countValidPaths(n, edges):
2 from collections import defaultdict
3 def sieve(n):
4 is_prime = [True] * (n + 1)
5 is_prime[0], is_prime[1] = False, False
6 for i in range(2, int(n**0.5) + 1):
7 if is_prime[i]:
8 for j in range(i*i, n + 1, i):
9 is_prime[j] = False
10 return is_prime
11
12 graph = defaultdict(list)
13 for u, v in edges:
14 graph[u].append(v)
15 graph[v].append(u)
16
17 primes = sieve(n)
18 valid_paths = 0
19
20 def dfs(node, parent, prime_count):
21 nonlocal valid_paths
22 if prime_count == 1:
23 valid_paths += 1
24 for neighbor in graph[node]:
25 if neighbor != parent:
26 dfs(neighbor, node, prime_count + (1 if primes[neighbor] else 0))
27
28 for i in range(1, n + 1):
29 dfs(i, -1, 1 if primes[i] else 0)
30
31 return valid_pathsℹ
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 graph representation and the recursion stack.
- 1Identifying prime numbers efficiently is crucial for this problem.
- 2Tree traversal techniques like DFS are essential for exploring paths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.