2
// made TreeNode class for simple implementation in recurring function8
public TreeNode(int id, int val) {11
child = new ArrayList<>();15
public int[] getCoprimes(int[] nums, int[][] edges) {16
// making tree/graph with edges17
TreeNode[] tr = new TreeNode[nums.length];18
for (int i = 0; i < nums.length; i++) tr[i] = new TreeNode(i, nums[i]);19
for (int[] x : edges) {20
tr[x[0]].child.add(tr[x[1]]);21
tr[x[1]].child.add(tr[x[0]]);23
// intializing answer array of length of tree's nodes which we will return24
int[] ans = new int[nums.length];26
// creating gcd to not compute gcd everytime27
boolean[][] gcd = new boolean[51][51];28
for (int i = 1; i <= 50; i++) {29
for (int j = i; j <= 50; j++) {30
if (find_gcd(i, j) == 1) {36
int[][] latest = new int[51][2];37
// instead of latest[][] as 2d array we can also use 2 arrays, one for who is latest ancestor &39
// in [][0] we will store height of tree so latest ancestor will be called40
// in [][1] we will store id of latest tree41
// initializing all to -142
for (int i = 0; i <= 50; i++) {46
find_closest_ancestor(tr[0], new TreeNode(-1, -1), ans, latest, gcd, 0);50
public void find_closest_ancestor(51
TreeNode root, TreeNode parent, int[] ans, int[][] latest, boolean[][] gcd, int height) {54
for (int i = 1; i <= 50; i++) {55
// if gcd [val][i] is true & latest[i][0] is latest ancestor i.e. it's height is more then57
if (gcd[val][i] && latest[latest_id][0] < latest[i][0]) latest_id = i;60
latest[latest_id][1]; // even if no latest ancestor found latest[id][1] is -1 by default62
// this is must we will save before state & after calling all it's child we will make it as it65
int pre_height = latest[val][0], pre_id = latest[val][1];66
latest[val][0] = height;67
latest[val][1] = root.id;69
// we recur with all child70
for (TreeNode root_child : root.child) {71
// we will check if we aren't going upward in tree so root.child!=parent then call function72
if (root_child != parent)73
find_closest_ancestor(root_child, root, ans, latest, gcd, height + 1);75
// as it was before we will put it back76
latest[val][0] = pre_height;77
latest[val][1] = pre_id;81
public int find_gcd(int a, int b) {83
return find_gcd(b, a % b);