Ctrl K

Nearest Coprime Ancestor

Hard
You are given a tree of n nodes numbered from 0 to n − 1, rooted at node 0. Its edges are listed in links: a pair [u, v] means nodes u and v are connected. Every node i carries a label labels[i]. Two numbers are **coprime** when their greatest common divisor is 1. The **ancestors** of a node are all nodes on its path to the root, not counting the node itself. For every node i, find its closest ancestor whose label is coprime with labels[i]. Return an array of length n holding that ancestor's number at position i, or -1 if there is none.
Example 1
labels=[3, 4, 9, 10], links=[[0, 1], [1, 2], [2, 3]] → [-1, 0, 1, 2]

Node 1 (4) is coprime with the root (3). Node 2 (9) is coprime with its parent, node 1 (4). Node 3 (10) and node 2 (9) share no divisor other than 1, so the answer is 2.

Example 2
labels=[6, 2, 4, 3], links=[[0, 1], [1, 2], [0, 3]] → [-1, -1, -1, -1]

Node 1 (2) has only the root (6) above it, and they share the factor 2. Node 2 (4) shares 2 with both node 1 and the root. Node 3 (3) and the root (6) are both divisible by 3. So no node has a suitable ancestor.

Example 3
labels=[1], links=[] → [-1]
Constraints
  • 1 ≤ n ≤ 10⁵
  • len(labels) = n
  • 1 ≤ labels[i] ≤ 50
  • len(links) = n − 1
  • 0 ≤ u, v < n, u ≠ v
  • The edges form a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSplit a Tree Into Equal Parts HardPaths With Exactly One Prime HardBiggest Shared-Factor Group HardMake One From Multiples HardOther Orders for the Same Search Tree Hard
loading Python…
Input
labels=[3, 4, 9, 10], links=[[0, 1], [1, 2], [2, 3]]
Expected
[-1, 0, 1, 2]

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