Imagine you're exploring a family tree where each person has a special numerical value, and you need to find their closest compatible ancestor!
Given a tree with n nodes numbered from 0 to n-1, where node 0 is the root, each node has an associated value. Two values are coprime if their greatest common divisor (GCD) equals 1 - meaning they share no common factors except 1.
Your task: For each node, find its closest ancestor (on the path to root) whose value is coprime with the current node's value. If no such ancestor exists, return -1 for that node.
Input: An array nums where nums[i] is the value of node i, and a 2D array edges representing tree connections.
Output: An array where result[i] is the closest coprime ancestor of node i, or -1 if none exists.
Input & Output
Constraints
- nums.length == n
- 1 โค n โค 105
- 1 โค nums[i] โค 50
- edges.length == n - 1
- edges[i].length == 2
- 0 โค ai, bi < n
- ai โ bi
- The given edges form a valid tree