Ctrl K

First Common Rooftop

Hard
Houses stand along a street, and 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.
Example 1
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.

Example 2
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.

Example 3
roofs=[6, 6, 6], pairs=[[0, 1]] → [-1]
Constraints
  • 1 ≤ len(roofs) ≤ 5 · 10⁴
  • 1 ≤ roofs[i] ≤ 10⁹
  • 1 ≤ len(pairs) ≤ 5 · 10⁴
  • pairs[q] = [a, b], 0 ≤ a, b ≤ len(roofs) - 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBest Pair Above the Bars HardSecond Larger to the Right HardCity Block Outline HardSmaller Values to the Right HardWindow Sums Within a Band Hard
loading Python…
Input
roofs=[3, 7, 2, 5, 9, 4], pairs=[[0, 2], [1, 3], [4, 5], [5, 5]]
Expected
[3, 4, -1, 5]

Run checks the first 3 tests in your browser. Submit checks all 114 tests on the server, hidden ones included.