Taro Logo

Count Valid Paths in a Tree

#3 Most AskedHard
0 views
Topics:
TreesRecursionGraphs

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:

  • The path (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.
  • Path (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 <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 <= ui, vi <= n
  • The input is generated such that edges represent a valid tree.

Solution


Clarifying Questions

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:

  1. What is the exact condition that the number of prime-valued node labels must satisfy in a valid path?
  2. What is the range of $n$ (the number of nodes) and the structure of the tree? Can we assume $n$ is up to $10^5$, or are there smaller limits?
  3. Are the node labels guaranteed to be uniquely numbered from $1$ to $n$, and can any node label itself be a prime number?
  4. How should paths be counted? Specifically, is a path considered undirected (does the path from A to B count as the same as B to A), and does a single node count as a valid path of length zero/one?
  5. What should be returned if no valid paths exist in the given tree? Should it return $0$?

Brute Force Solution

Approach

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:

  1. Precompute prime numbers up to n using the Sieve of Eratosthenes.
  2. Build an adjacency list representation of the given tree.
  3. Initialize a Disjoint Set Union structure to maintain connected components of non-prime nodes.
  4. Iterate over all edges and unite adjacent non-prime nodes to form connected components and record their sizes.
  5. Iterate over every prime node and find the sizes of the non-prime components connected to its neighbors.
  6. Add paths starting at the prime node into each connected non-prime component, as well as paths connecting two distinct non-prime components through the prime node.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n * alpha(n)) – Sieving takes O(n log log n) time. Grouping non-prime nodes with DSU and traversing the neighbors of each prime takes O(n * alpha(n)) time, where alpha is the inverse Ackermann function, resulting in an overall near-linear runtime.
Space Complexity
O(n) – We store the adjacency list, the prime boolean array, and the DSU parent and size arrays, all of which require linear space with respect to n.

Optimal Solution

Approach

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:

  1. Precompute prime numbers up to n using a sieve method.
  2. Build the tree's adjacency list from the provided edges.
  3. Initialize a disjoint set union data structure to group non-prime nodes connected by edges.
  4. Iterate over all edges to union endpoints that are both non-prime.
  5. For each prime node, find the sizes of all adjacent non-prime connected components.
  6. Add the paths starting at the prime node, as well as paths connecting pairs of distinct non-prime branches through the prime node.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n * alpha(n)) – Sieve of Eratosthenes takes O(n log log n) time. Grouping non-prime nodes and inspecting adjacent components around each prime node takes O(n * alpha(n)) time, where alpha is the inverse Ackermann function.
Space Complexity
O(n) – The sieve array, adjacency list, and disjoint set union arrays each require O(n) space to store information for n nodes.

Edge Cases

Tree with a single node where n equals 1
How to Handle:
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
How to Handle:
The algorithm must correctly count zero valid paths without running into runtime errors.
Tree with all prime-valued node labels
How to Handle:
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
How to Handle:
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
How to Handle:
Employ an efficient linear time tree DP combined with a precomputed prime sieve to ensure optimal scalability.
Disconnected graph or invalid edge definitions provided
How to Handle:
Validate the input tree structure to ensure it forms a single connected component before running tree traversal.
Integer overflow during path combinations counting
How to Handle:
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
How to Handle:
The centroid decomposition or tree DP must correctly aggregate cross-branch paths through the central root.
0/3 completed