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
- 55 lines of Java from the credited upstream file 1766.java.
- The implementation visibly relies on sequence storage, work queue.
- 5 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 public int[] getCoprimes(int[] nums, int[][] edges) {3 int[] ans = new int[nums.length];4 Arrays.fill(ans, -1);5 List<Integer>[] tree = new List[nums.length];6 7 Deque<Pair<Integer, Integer>>[] stacks = new Deque[MAX + 1];8 9 for (int i = 0; i < nums.length; ++i)10 tree[i] = new ArrayList<>();11 12 for (int i = 1; i <= MAX; ++i)13 stacks[i] = new ArrayDeque<>();14 15 for (int[] edge : edges) {16 final int u = edge[0];17 final int v = edge[1];18 tree[u].add(v);19 tree[v].add(u);20 }21 22 dfs(tree, 0, -1, 0, nums, stacks, ans);23 return ans;24 }25 26 private static final int MAX = 50;27 28 private void dfs(List<Integer>[] tree, int u, int prev, int depth, int[] nums,29 Deque<Pair<Integer, Integer>>[] stacks, int[] ans) {30 ans[u] = getAncestor(u, stacks, nums);31 stacks[nums[u]].push(new Pair<>(u, depth));32 33 for (final int v : tree[u])34 if (v != prev)35 dfs(tree, v, u, depth + 1, nums, stacks, ans);36 37 stacks[nums[u]].pop();38 }39 40 private int getAncestor(int u, Deque<Pair<Integer, Integer>>[] stacks, int[] nums) {41 int maxNode = -1;42 int maxDepth = -1;43 for (int i = 1; i <= MAX; ++i)44 if (!stacks[i].isEmpty() && stacks[i].peek().getValue() > maxDepth && gcd(nums[u], i) == 1) {45 maxNode = stacks[i].peek().getKey();46 maxDepth = stacks[i].peek().getValue();47 }48 return maxNode;49 }50 51 private int gcd(int a, int b) {52 return b == 0 ? a : gcd(b, a % b);53 }54}55