- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 70 lines of Python from the credited upstream file 2940.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4@dataclass5class IndexedQuery:6 queryIndex: int7 a: int 8 b: int 9 10 def __iter__(self):11 yield self.queryIndex12 yield self.a13 yield self.b14 15 16class Solution:17 18 def leftmostBuildingQueries(19 self,20 heights: list[int],21 queries: list[list[int]],22 ) -> list[int]:23 ans = [-1] * len(queries)24 25 26 stack = []27 28 29 heightsIndex = len(heights) - 130 for queryIndex, a, b in sorted([IndexedQuery(i, min(a, b), max(a, b))31 for i, (a, b) in enumerate(queries)],32 key=lambda x: -x.b):33 if a == b or heights[a] < heights[b]:34 35 36 ans[queryIndex] = b37 else:38 39 40 while heightsIndex > b:41 42 43 44 45 while stack and heights[stack[-1]] <= heights[heightsIndex]:46 stack.pop()47 stack.append(heightsIndex)48 heightsIndex -= 149 50 51 j = self._lastGreater(stack, a, heights)52 if j != -1:53 ans[queryIndex] = stack[j]54 55 return ans56 57 def _lastGreater(self, A: list[int], target: int, heights: list[int]):58 """59 Returns the last index i in A s.t. heights[A.get(i)] is > heights[target].60 """61 l = -162 r = len(A) - 163 while l < r:64 m = (l + r + 1) 265 if heights[A[m]] > heights[target]:66 l = m67 else:68 r = m - 169 return l70