- 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
- 65 lines of C++ from the credited upstream file 2940.cpp.
- The implementation visibly relies on sequence storage.
- 4 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.
1struct IndexedQuery {2 int queryIndex;3 int a; 4 int b; 5};6 7class Solution {8 public:9 10 vector<int> leftmostBuildingQueries(vector<int>& heights,11 vector<vector<int>>& queries) {12 vector<int> ans(queries.size(), -1);13 14 15 vector<int> stack;16 17 18 int heightsIndex = heights.size() - 1;19 for (const auto& [queryIndex, a, b] : getIndexedQueries(queries)) {20 if (a == b || heights[a] < heights[b]) {21 22 23 ans[queryIndex] = b;24 } else {25 26 27 while (heightsIndex > b) {28 29 30 31 32 while (!stack.empty() &&33 heights[stack.back()] <= heights[heightsIndex])34 stack.pop_back();35 stack.push_back(heightsIndex--);36 }37 38 39 if (const auto it = upper_bound(40 stack.rbegin(), stack.rend(), a,41 [&](int a, int b) { return heights[a] < heights[b]; });42 it != stack.rend())43 ans[queryIndex] = *it;44 }45 }46 47 return ans;48 }49 50 private:51 vector<IndexedQuery> getIndexedQueries(const vector<vector<int>>& queries) {52 vector<IndexedQuery> indexedQueries;53 for (int i = 0; i < queries.size(); ++i) {54 55 const int a = min(queries[i][0], queries[i][1]);56 const int b = max(queries[i][0], queries[i][1]);57 indexedQueries.push_back({i, a, b});58 }59 ranges::sort(60 indexedQueries,61 [](const IndexedQuery& a, const IndexedQuery& b) { return a.b > b.b; });62 return indexedQueries;63 }64};65