![]() |
VOOZH | about |
Given a tree with N nodes and (N - 1) edges, where the nodes are assigned values from 1 to N, and the root node is 1. The task is to determine if there exists a subtree within the given tree that contains exactly K prime-numbered nodes.
Examples:
Input: N = 5, K = 2, edges[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}}
Output: 1
Explanation: Below image represents subtree containing 2 primes: 2 and 5
Input: N = 7, K = 5, edges = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}, {3, 7}}
Output: 0
Explanation: Below image shows that there is no subtree containing 5 primes:
Approach: To solve the problem, follow the below idea:
The main idea is to use a Depth-First Search (DFS) to traverse the tree, counting the prime-numbered nodes in each subtree. The count is checked for equality with K, and if found, the answer is set to true, and here we can use the Sieve of Eratosthenes to efficiently identify prime numbers.
Step-by-step algorithm:
Below is the implementation of the algorithm:
1
Time Complexity: O(N * log(log(N))), where N is the number of nodes in the tree.
Auxiliary Space: O(N)