LeetCode 2940, Hard. Topics: Array, Binary Search, Stack, Binary Indexed Tree, Segment Tree, Heap (Priority Queue), Monotonic Stack. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:
Problem
You are given a 0-indexed array heights of positive integers, where heights[i] represents the height of the ith building.
If a person is in building i, they can move to any other building j if and only if i < j and heights[i] < heights[j].
You are also given another array queries where queries[i] = [a_i, b_i]. On the ith query, Alice is in building a_i while Bob is in building b_i.
Return an array ans where ans[i] is the index of the leftmost building where Alice and Bob can meet on the ith query. If Alice and Bob cannot move to a common building on query i, set ans[i] to -1.
Examples
Constraints
- 1 <= heights.length <= 5 * 10^4
- 1 <= heights[i] <= 10^9
- 1 <= queries.length <= 5 * 10^4
- queries[i] = [a_i, b_i]
- 0 <= a_i, b_i <= heights.length - 1
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026