Ctrl K

Paths With Exactly One Prime

Hard
You are given a tree with n nodes numbered 1 to n. The list links of length n - 1 holds its edges: links[i] = [u, v] connects nodes u and v. Take two different nodes a and b and the unique path between them in the tree, endpoints included. The path counts if exactly one of the node numbers on it is prime. Return the number of paths that count. The paths a–b and b–a are the same path and must be counted once.
Example 1
n=4, links=[[1, 2], [2, 3], [3, 4]] → 2

The primes are 2 and 3. Exactly one prime lies only on the paths 1–2 and 3–4; every other path has either none or both.

Example 2
n=5, links=[[1, 2], [1, 3], [1, 4], [1, 5]] → 6

The paths 1–2, 1–3, 1–5 work, and so do the paths from 4 to 2, 3 and 5 through the centre 1, for 6 in total.

Example 3
n=1, links=[] → 0

The tree has a single node, so there is no path between two different nodes.

Constraints
  • 1 ≤ n ≤ 10⁵
  • len(links) = n − 1
  • 1 ≤ u, v ≤ n
  • The edges form a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNearest Coprime Ancestor HardHeaviest Path in a Tree HardDistance Totals in a Road Tree HardFewest Guards on a Tree HardHeaviest Search Subtree Hard
loading Python…
Input
n=4, links=[[1, 2], [2, 3], [3, 4]]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 36 tests on the server, hidden ones included.