Tree of Coprimes - Problem

There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.

To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.

Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.

An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.

Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.

Input & Output

Example 1 — Basic Tree
$ Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]
Output: [-1,0,0,1]
💡 Note: Node 0 is root (no ancestors). Node 1: gcd(3,2)=1, so ancestor is 0. Node 2: gcd(3,3)=3≠1 but gcd(3,2)=1, so ancestor is 0. Node 3: gcd(2,3)=1, so ancestor is 1.
Example 2 — Single Node
$ Input: nums = [5], edges = []
Output: [-1]
💡 Note: Only one node, which is the root, so no ancestors exist.
Example 3 — Linear Chain
$ Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
Output: [-1,0,0,1,0,0,0]
💡 Note: Complex tree structure where each node finds its closest coprime ancestor through DFS traversal.

Constraints

  • nums.length == n
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i] ≤ 50
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 ≤ ai, bi < n
  • The input represents a valid tree

Visualization

Tap to expand
Tree of Coprimes Problem OverviewInput Tree0:21:32:33:2Coprime CheckNode 1: gcd(3,2) = 1 ✓Ancestor: 0Node 2: gcd(3,3) = 3 ✗but gcd(3,2) = 1 ✓Ancestor: 0Output[-1, 0, 0, 1]Coprime ancestorsAlgorithm: DFS with ancestor stack trackingFor each node, find closest ancestor with gcd(node_val, ancestor_val) = 1Time: O(n × A × log V) | Space: O(n + A)
Understanding the Visualization
1
Input Tree
Tree with nodes having values: [2,3,3,2]
2
Process
For each node, find closest ancestor with coprime value
3
Output
Array of closest coprime ancestor indices
Key Takeaway
🎯 Key Insight: Use DFS with ancestor stack to efficiently track coprime relationships during tree traversal
Asked in
Google 25 Facebook 18 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen