Tree Path GCD
Updated
Problem statement
You are given a tree with n nodes numbered from 0 to n - 1 and rooted at node 0. The tree is given as an array parent, where parent[i] is the parent of node i and parent[0] == -1. Each node i holds a positive integer values[i].
You are also given an array queries, where queries[j] = [uj, vj]. For each query, find the greatest common divisor (GCD) of the values of all nodes on the path between uj and vj, including both ends. If uj == vj, the path is just that one node.
Return an array answer where answer[j] is the result of the j-th query.
Function
treePathGcd(parent: int[], values: int[], queries: int[][]) → int[]Examples
Example 1
parent = [-1,0,0,1,1,2,2]values = [12,18,8,6,24,4,20]queries = [[3,4],[3,5],[4,4],[6,2],[4,0]]return = [6,2,24,4,6]Node 0 has children 1 and 2, node 1 has children 3 and 4, and node 2 has children 5 and 6. The path from 3 to 4 is 3 - 1 - 4, with values 6, 18 and 24, so the GCD is 6. The path from 3 to 5 is 3 - 1 - 0 - 2 - 5, with values 6, 18, 12, 8 and 4, so the GCD is 2. The query [4, 4] is the single node 4, so the answer is its value 24. The path from 6 to 2 has values 20 and 8, so the GCD is 4. The path from 4 to 0 has values 24, 18 and 12, so the GCD is 6.
Example 2
parent = [-1,2,0,1]values = [30,42,18,70]queries = [[3,0],[1,2],[3,1]]return = [2,6,14]Here parent[1] = 2, so a parent can have a larger number than its child. The tree is the chain 0 - 2 - 1 - 3. The path from 3 to 0 is the whole chain, with values 70, 42, 18 and 30, so the GCD is 2. The path from 1 to 2 has values 42 and 18, so the GCD is 6. The path from 3 to 1 has values 70 and 42, so the GCD is 14.
Example 3
parent = [-1]values = [1000000000]queries = [[0,0]]return = [1000000000]The tree has one node, and the only query asks for the path from node 0 to itself. The answer is its value, 1000000000.
Constraints
n == parent.length == values.length1 <= n <= 10^5parent[0] == -1, and0 <= parent[i] < nfori >= 1. Following parents from any node reaches node0. A parent may have a larger number than its child.1 <= values[i] <= 10^91 <= queries.length <= 10^4queries[j].length == 20 <= uj, vj < n
Similar questions at other companies
- Count Stepping Numbers In RangeAmazon · PHONE SCREEN
- Frog Position After T SecondsInMobi · PHONE SCREENInMobi interview questions
- Maximum Signal Walk in a Server TreeTower Research Capital · OA
- Prime Tree City LabelingsRippling · OARippling interview questions
- Company Score with Manager CapsIndeed · OAIndeed interview questions
- Count Level-Order Traversals of a TreeBank of America · OABank of America interview questions
- Count Distinct Binary Search TreesC3.ai · OAC3.ai interview questions
- Longest Alternating a/b Path in a TreeHudson River Trading · OAHudson River Trading interview questions
- Minimum Cameras to Monitor a Binary TreeOYO Rooms · PHONE SCREEN
- Grid Robot Route with Charging PrioritiesUber · PHONE SCREEN · ONSITE INTERVIEWUber interview questions