#2940
Find Building Where Alice and Bob Can Meet
HardArrayBinary SearchStackBinary Indexed TreeSegment TreeHeap (Priority Queue)Monotonic StackStack for finding the next greater element.Array manipulation for efficient query handling.
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + q) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + q)Space O(n)
We can preprocess the heights to find the next taller building for each building, allowing us to quickly determine where Alice and Bob can meet without checking each building for every query.
⚙️
Algorithm
5 steps- 1Step 1: Create an array nextTaller to store the index of the next taller building for each building.
- 2Step 2: Use a stack to efficiently find the next taller building for each building in a single pass.
- 3Step 3: For each query, use the nextTaller array to find the leftmost building they can both reach.
- 4Step 4: If heights[a] < heights[next] and heights[b] < heights[next], return next.
- 5Step 5: If no valid building is found, return -1.
solution.py21 lines
1def findMeetingBuildings(heights, queries):
2 n = len(heights)
3 nextTaller = [-1] * n
4 stack = []
5 for i in range(n):
6 while stack and heights[stack[-1]] < heights[i]:
7 nextTaller[stack.pop()] = i
8 stack.append(i)
9 ans = []
10 for a, b in queries:
11 if a > b:
12 a, b = b, a
13 leftmost = -1
14 next = nextTaller[a]
15 while next != -1:
16 if heights[b] < heights[next]:
17 leftmost = next
18 break
19 next = nextTaller[next]
20 ans.append(leftmost)
21 return ansℹ
Complexity note: The preprocessing step to find the next taller building takes O(n), and each query can be resolved in O(1) time on average, leading to O(n + q) overall.
- 1Understanding the movement constraints is crucial for determining valid meeting points.
- 2Preprocessing data can significantly reduce the time complexity for multiple queries.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.