VOOZH about

URL: https://www.geeksforgeeks.org/dsa/subtree-with-exactly-k-primes/

⇱ Subtree with exactly K primes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subtree with exactly K primes

Last Updated : 23 Jul, 2025

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

👁 subtree


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:


👁 subtree2-(1)

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:

  • Create an adjacency list adj for the tree and initialize a prime list prime from 0 to n, marking 0 and 1 as not prime using the Sieve of Eratosthenes.
  • Define a DFS function (DFS(node, adj, prime, vis, ans, k)) that marks the current node as visited, counts prime nodes in its subtree, and increments ans if the count equals k.
  • Recursively call the function for unvisited neighbors of the current node.
  • Initialize a visited list vis and an answer list ans and call DFS for the root node (e.g., node 1).
  • Check if the value in the ans list is greater than 0 and return true if yes, else return false.

Below is the implementation of the algorithm:


Output
1

Time Complexity: O(N * log(log(N))), where N is the number of nodes in the tree.
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: