You are given a 0-indexed array heights of positive integers, where heights[i] represents the height of the i-th 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 i-th 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 i-th query. If Alice and Bob cannot move to a common building on query i, set ans[i] to -1.

Input & Output

Example 1 — Basic Meeting
$ Input: heights = [6,4,8,5,2,7], queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]
Output: [2,5,-1,-1,2]
💡 Note: Query [0,1]: Alice at 6, Bob at 4. First building both can reach is index 2 (height 8). Query [0,3]: Alice needs height > 6, Bob needs > 5, first such building is index 5 (height 7). Query [2,4]: Alice at 8, Bob at 2, but no building after index 4 is taller than 8. Query [3,4]: Bob at 2, Alice at 5, no building after index 4 is taller than 5. Query [2,2]: Same position, return 2.
Example 2 — Direct Reach
$ Input: heights = [5,3,8,2,6,1,4,6], queries = [[0,7],[3,5],[2,6]]
Output: [7,5,2]
💡 Note: Query [0,7]: Alice at height 5, Bob at height 6. Since Bob's building (index 7) is to the right and taller than Alice's, they can meet at index 7. Query [3,5]: Alice at height 2, Bob at height 1. Alice can reach Bob's position since index 5 > 3 and height 1 < 2 is false, but 6 > 2, so answer is 5. Query [2,6]: Alice already at height 8, Bob at height 4, Alice's position works.
Example 3 — No Meeting Possible
$ Input: heights = [1,2,1,2], queries = [[0,0],[1,3]]
Output: [0,-1]
💡 Note: Query [0,0]: Same building, return 0. Query [1,3]: Alice at height 2 (index 1), Bob at height 2 (index 3). No building after index 3 exists, so they cannot meet at a common taller building.

Constraints

  • 1 ≤ heights.length ≤ 5 × 104
  • 1 ≤ heights[i] ≤ 109
  • 1 ≤ queries.length ≤ 5 × 104
  • queries[i] = [ai, bi]
  • 0 ≤ ai, bi ≤ heights.length - 1

Visualization

Tap to expand
Alice and Bob Building Meeting Problem648527012345ABQuery [0,1]: Alice at building 0 (height 6), Bob at building 1 (height 4)Both can meet at building 2 (height 8) - Answer: 2
Understanding the Visualization
1
Input Buildings
Array of building heights with Alice and Bob at specific positions
2
Movement Rules
Can only move right to taller buildings (i < j and heights[i] < heights[j])
3
Find Meeting
Leftmost building both can reach, or -1 if impossible
Key Takeaway
🎯 Key Insight: Find the leftmost building that is taller than both starting positions and has an index greater than both
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen