Do a DFS and store all nodes values on path from 1 to current node in an array
traverse in reverse and find closest node which is coprime to current node value
To be honest, it wont help. You would get something quite different. Maybe something you’re weak at. Its google after all, they know where u weak at xD
May be the test cases were weak… in the worst case a tree can be like an normal list…in that case it should time out… the values of nodes are <= 100 (from constraints)
so you could just find the values which are coprime with the current node’s value easily… and for each such value we can find the distance between such a node and the current node easily… by this way the time complexity will be O(N)
I gave my coding round today. Just wanted to confirm that we only have to click the submit button beside compile and test, and if all test cases pass we are done, right? I couldn’t see my score and hence confused.
If you want to know a better solution, then we can use sparse table to store the gcd from i to 2^j th parent. Now If we iterate over every element and then do a binary search it would just take n*log(n)*log(n) time. Is this solution cool (We can apply Binary search as gcd will be decreasing function while moving up the ancestors)