Find Building Where Alice and Bob Can Meet

Hard Topics Company Tags

Building i has height heights[i]. From building i, a person may move to building j only when j > i and heights[j] > heights[i]. A person may also stay at their starting building.

For each query [a, b], Alice starts at a and Bob starts at b. Find the smallest building index they can both reach. Return -1 for that query if they cannot meet.

Return the answers in the same order as queries. Each query is independent.

Example 1:

Input: heights = [3,1,4,2,5]
queries = [[0,1],[1,3],[4,2]]

Output: [2,3,4]

Explanation: From buildings 0 and 1, both can reach building 2, the first building taller than both starting heights. From 1 and 3, Alice can move directly to 3. From 4 and 2, Bob can move directly to 4.

Example 2:

Input: heights = [5,5,5]
queries = [[0,1],[2,2],[2,0]]

Output: [-1,2,-1]

Explanation: Equal heights do not permit a move. Distinct starting buildings cannot meet here, but the query [2,2] already places both people at building 2.

Example 3:

Input: heights = [2,6,3,7]
queries = [[2,0],[1,2],[3,1]]

Output: [2,3,3]

Explanation: For [2,0], the person at 0 can move to 2, so the answer is 2. For [1,2], both can reach the taller building 3. For [3,1], the person at 1 can move directly to 3.

Constraints:

  • 1 <= heights.length <= 50000
  • 1 <= heights[i] <= 1000000000
  • 1 <= queries.length <= 50000
  • Every query has two indices, each between 0 and heights.length - 1.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.