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.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.
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.
labels=[1], links=[] → [-1]
labels=[3, 4, 9, 10], links=[[0, 1], [1, 2], [2, 3]]
[-1, 0, 1, 2]
Run checks the first 3 tests in your browser. Submit checks all 26 tests on the server, hidden ones included.