roofs[i] is the roof height of house i (0-based). A free runner can jump from roof i to roof j only if j is further right (i < j) and higher (roofs[i] < roofs[j]). Any number of jumps is allowed.
In query pairs[q] = [a, b], one person stands on roof a and another on roof b. Find the leftmost roof where they can meet: each of them either already stands there or can get there. If there is no such roof, the answer is -1.
Return the answers to all queries in their original order.roofs=[3, 7, 2, 5, 9, 4], pairs=[[0, 2], [1, 3], [4, 5], [5, 5]] → [3, 4, -1, 5]
Pair 0 and 2: roof 0 (height 3) cannot reach roof 2 (height 2), but roof 3 with height 5 is taller than both, so the answer is 3. Pair 1 and 3: roof 3 is lower than roof 1, and the first roof to the right taller than 7 is roof 4. Pair 4 and 5: nothing to the right is taller than 9, so -1. Pair 5 and 5: they already stand on the same roof.
roofs=[1, 2, 3], pairs=[[2, 0], [0, 1]] → [2, 1]
The roofs rise from left to right, so the left one can always go straight to the right one: the answers are 2 and 1.
roofs=[6, 6, 6], pairs=[[0, 1]] → [-1]
roofs=[3, 7, 2, 5, 9, 4], pairs=[[0, 2], [1, 3], [4, 5], [5, 5]]
[3, 4, -1, 5]
Run checks the first 3 tests in your browser. Submit checks all 114 tests on the server, hidden ones included.