Amazon all India hiring | Hackathon | May 2019

I faced this question recently in a hackthon conducted by Amazon India.
For some reason I couldn't solve it in Java and to switch for cpp. I wanna learn more approaches to solve this.

Question statement:
Given a tree with N vertices and N-1 edges. i'th node has a value equal to A(i) (array indexing starts from 1). Given Q queries of format, L X, find such node which lies at level
L mod (maxDepth + 1) and has value which is just greater than or equal to X.
Answer to the query is the smallest value of such node and if no such node exists answer is -1.

Note: Root of the tree is 1 and its level is 0, MaxDepth is the maximum depth of the tree.

Input

First line: N, Q i.e no of vertices and no of queries respectively.

Second line: N space separated integers defining array A
Next N - 1 lines: u and v, meaning there is an edge between vertex u and v.
Next Q lines: Queries of type L X

Example:

6 3
1 5 7 8 6 10
1 2
1 3
2 4
2 5
3 6
1 6
2 7
6 2

Output:

7
8
-1
Comments (3)