Count Valid Paths in a Tree - Problem
Count Valid Paths in a Tree
Imagine you're exploring a mystical tree where each node is labeled with a number from 1 to n. Your quest is to find all the magical paths - those that contain exactly one prime number along the way!
You're given:
• An integer
• A 2D array
Your mission: Count how many valid paths exist in this tree.
A path from node
Example: In a tree with nodes [1,2,3,4] where 2 and 3 are prime, a path containing nodes [1,2,4] would be valid (exactly one prime: 2), but a path [2,3,4] would not be valid (two primes: 2 and 3).
Imagine you're exploring a mystical tree where each node is labeled with a number from 1 to n. Your quest is to find all the magical paths - those that contain exactly one prime number along the way!
You're given:
• An integer
n representing the total number of nodes• A 2D array
edges where each edge connects two nodes, forming a treeYour mission: Count how many valid paths exist in this tree.
A path from node
a to node b is considered valid if the sequence of node labels along this path contains exactly one prime number. Remember that paths (a,b) and (b,a) are the same path and should only be counted once!Example: In a tree with nodes [1,2,3,4] where 2 and 3 are prime, a path containing nodes [1,2,4] would be valid (exactly one prime: 2), but a path [2,3,4] would not be valid (two primes: 2 and 3).
Input & Output
example_1.py — Small Tree
$
Input:
n = 4, edges = [[1,2],[1,3],[2,4]]
›
Output:
4
💡 Note:
The valid paths are: (1,2), (1,3), (2,4), (3,4). Each contains exactly one prime number. Path (1,2) has prime 2, path (1,3) has prime 3, path (2,4) has prime 2, and path (3,4) passes through nodes 3→1→2→4 containing primes 3 and 2, so it's invalid. Actually, direct paths: (1,2) has prime 2, (1,3) has prime 3, (2,4) has prime 2, and (1,4) passes through 1→2→4 with prime 2.
example_2.py — Linear Tree
$
Input:
n = 5, edges = [[1,2],[2,3],[3,4],[4,5]]
›
Output:
6
💡 Note:
In this linear tree 1-2-3-4-5, valid paths with exactly one prime are: (1,2), (1,3), (2,4), (2,5), (4,5), (3,4). Path (2,3) has two primes so it's invalid.
example_3.py — No Prime Tree
$
Input:
n = 3, edges = [[1,4],[4,6]]
›
Output:
0
💡 Note:
None of the nodes (1,4,6) are prime numbers, so no path contains exactly one prime. All paths have zero primes.
Constraints
- 1 ≤ n ≤ 105
- edges.length == n - 1
- edges[i].length == 2
- 1 ≤ ui, vi ≤ n
- The input represents a valid tree
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code