Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
For each query <code>[x, y]</code>, if <code>x > y</code>, swap <code>x</code> and <code>y</code>. Now, we can assume that <code>x <= y</code>.
For each query <code>[x, y]</code>, if <code>x == y</code> or <code>heights[x] < heights[y]</code>, then the answer is <code>y</code> since <code>x ≤ y</code>.
Otherwise, we need to find the smallest index <code>t</code> such that <code>y < t</code> and <code>heights[x] < heights[t]</code>. Note that <code>heights[y] <= heights[x]</code>, so <code>heights[x] < heights[t]</code> is a sufficient condition.
To find index <code>t</code> for each query, sort the queries in descending order of <code>y</code>. Iterate over the queries while maintaining a monotonic stack which we can binary search over to find index <code>t</code>.