Approach
Depth-first search
For Tree of Coprimes, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 33 lines of Python from the credited upstream file 1766.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def getCoprimes(self, nums: list[int], edges: list[list[int]]) -> list[int]:3 MAX = 504 ans = [-1] * len(nums)5 tree = [[] for _ in range(len(nums))]6 7 stacks = [[] for _ in range(MAX + 1)]8 9 for u, v in edges:10 tree[u].append(v)11 tree[v].append(u)12 13 def getAncestor(u: int) -> int:14 maxNode = -115 maxDepth = -116 for i, stack in enumerate(stacks):17 if stack and stack[-1][1] > maxDepth and math.gcd(nums[u], i) == 1:18 maxNode, maxDepth = stack[-1]19 return maxNode20 21 def dfs(u: int, prev: int, depth: int) -> int:22 ans[u] = getAncestor(u)23 stacks[nums[u]].append((u, depth))24 25 for v in tree[u]:26 if v != prev:27 dfs(v, u, depth + 1)28 29 stacks[nums[u]].pop()30 31 dfs(0, -1, 0)32 return ans33