There is an undirected tree with n nodes labeled from 1 to n. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree.
Return the number of valid paths in the tree.
A path (a, b) is valid if there exists exactly one prime number among the node labels in the path from a to b.
Note that:
(a, b) is a sequence of distinct nodes starting with node a and ending with node b such that every two adjacent nodes in the sequence share an edge in the tree.(a, b) and path (b, a) are considered the same and counted only once.Example 1:
Input: n = 5, edges = [[1,2],[1,3],[2,4],[2,5]] Output: 4 Explanation: The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (2, 4) since the path from 2 to 4 contains prime number 2. It can be shown that there are only 4 valid paths.
Example 2:
Input: n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]] Output: 6 Explanation: The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (1, 6) since the path from 1 to 6 contains prime number 3. - (2, 4) since the path from 2 to 4 contains prime number 2. - (3, 6) since the path from 3 to 6 contains prime number 3. It can be shown that there are only 6 valid paths.
Constraints:
1 <= n <= 105edges.length == n - 1edges[i].length == 21 <= ui, vi <= nedges represent a valid tree.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
A valid path contains exactly one prime number, which means the prime node acts as a bridge between two non-prime components or connects a non-prime component to itself. We can precompute all prime numbers up to n and group contiguous non-prime nodes using a Disjoint Set Union structure. For each prime node, we count how many paths can be formed either between the prime and an adjacent non-prime component or between two different non-prime components connected through the prime.
Here's how the algorithm would work step-by-step:
def count_valid_paths(n: int, edges: list[list[int]]) -> int:
# Precompute prime numbers up to n using a sieve.
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
for number in range(2, int(n**0.5) + 1):
if is_prime[number]:
for multiple in range(number * number, n + 1, number):
is_prime[multiple] = False
adjacency = [[] for _ in range(n + 1)]
for u_node, v_node in edges:
adjacency[u_node].append(v_node)
adjacency[v_node].append(u_node)
# Use disjoint set union to group adjacent non-prime nodes.
parent = list(range(n + 1))
size = [1] * (n + 1)
def find(node_id: int) -> int:
while parent[node_id] != node_id:
parent[node_id] = parent[parent[node_id]]
node_id = parent[node_id]
return node_id
def union(node_a: int, node_b: int) -> None:
root_a = find(node_a)
root_b = find(node_b)
if root_a != root_b:
if size[root_a] < size[root_b]:
root_a, root_b = root_b, root_a
parent[root_b] = root_a
size[root_a] += size[root_b]
for u_node, v_node in edges:
if not is_prime[u_node] and not is_prime[v_node]:
union(u_node, v_node)
# Count valid paths having exactly one prime node as an endpoint or internal node.
total_valid_paths = 0
for prime_candidate in range(2, n + 1):
if not is_prime[prime_candidate]:
continue
component_sizes = []
for neighbor in adjacency[prime_candidate]:
if not is_prime[neighbor]:
component_sizes.append(size[find(neighbor)])
sum_sizes = sum(component_sizes)
total_valid_paths += sum_sizes
current_pair_sum = 0
for comp_size in component_sizes:
total_valid_paths += comp_size * current_pair_sum
current_pair_sum += comp_size
return total_valid_paths
This problem requires counting paths in a tree that contain exactly one prime-labeled node. Every valid path must either start at a prime node and extend into a non-prime component, or pass through exactly one prime node connecting two non-prime components. By grouping contiguous non-prime nodes using disjoint-set union, we can compute the answer by iterating over each prime node and evaluating the sizes of its adjacent non-prime components.
Here's how the algorithm would work step-by-step:
def count_valid_paths(n: int, edges: list[list[int]]) -> int:
# Precompute primes up to n using the Sieve of Eratosthenes
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
for number in range(2, int(n**0.5) + 1):
if is_prime[number]:
for multiple in range(number * number, n + 1, number):
is_prime[multiple] = False
adjacency_list = [[] for _ in range(n + 1)]
for node_u, node_v in edges:
adjacency_list[node_u].append(node_v)
adjacency_list[node_v].append(node_u)
# Use Disjoint Set Union to group non-prime nodes into connected components
parent = list(range(n + 1))
size = [1] * (n + 1)
def find(element: int) -> int:
root = element
while root != parent[root]:
root = parent[root]
curr = element
while curr != root:
nxt = parent[curr]
parent[curr] = root
curr = nxt
return root
def union(element_a: int, element_b: int) -> None:
root_a = find(element_a)
root_b = find(element_b)
if root_a != root_b:
if size[root_a] < size[root_b]:
root_a, root_b = root_b, root_a
parent[root_b] = root_a
size[root_a] += size[root_b]
for node_u, node_v in edges:
if not is_prime[node_u] and not is_prime[node_v]:
union(node_u, node_v)
# Count valid paths that pass through or terminate at each prime node
total_valid_paths = 0
for node in range(2, n + 1):
if not is_prime[node]:
continue
branch_sizes = []
for neighbor in adjacency_list[node]:
if not is_prime[neighbor]:
branch_sizes.append(size[find(neighbor)])
sum_sizes = sum(branch_sizes)
total_valid_paths += sum_sizes
current_product_sum = 0
running_sum = 0
for branch_size in branch_sizes:
current_product_sum += running_sum * branch_size
running_sum += branch_size
total_valid_paths += current_product_sum
return total_valid_paths
| Case | How to Handle |
|---|---|
| Tree with a single node where n equals 1 | Return zero since a path requires at least two distinct nodes or check if the single node itself satisfies the prime condition. |
| Tree with no prime-valued node labels | The algorithm must correctly count zero valid paths without running into runtime errors. |
| Tree with all prime-valued node labels | Combinatorics formulas must account for every possible path contributing to the valid prime count condition. |
| Highly skewed tree resembling a linked list of maximum constraints | Use an iterative approach or increase stack limits to prevent stack overflow errors from deep recursion. |
| Maximum number of nodes reaching up to one hundred thousand | Employ an efficient linear time tree DP combined with a precomputed prime sieve to ensure optimal scalability. |
| Disconnected graph or invalid edge definitions provided | Validate the input tree structure to ensure it forms a single connected component before running tree traversal. |
| Integer overflow during path combinations counting | Use 64-bit integer types for all path accumulation variables to safely handle large tree structures. |
| Branching factor where all nodes connect to a single root star graph | The centroid decomposition or tree DP must correctly aggregate cross-branch paths through the central root. |