- 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
- 72 lines of Java from the credited upstream file 2940.java.
- The implementation visibly relies on sequence storage.
- 5 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.
1class Solution {2 3 public int[] leftmostBuildingQueries(int[] heights, int[][] queries) {4 IndexedQuery[] indexedQueries = getIndexedQueries(queries);5 int[] ans = new int[queries.length];6 Arrays.fill(ans, -1);7 8 9 List<Integer> stack = new ArrayList<>();10 11 12 int heightsIndex = heights.length - 1;13 for (IndexedQuery indexedQuery : indexedQueries) {14 final int queryIndex = indexedQuery.queryIndex;15 final int a = indexedQuery.a;16 final int b = indexedQuery.b;17 if (a == b || heights[a] < heights[b]) {18 19 20 ans[queryIndex] = b;21 } else {22 23 24 while (heightsIndex > b) {25 26 27 28 29 while (!stack.isEmpty() && heights[stack.get(stack.size() - 1)] <= heights[heightsIndex])30 stack.remove(stack.size() - 1);31 stack.add(heightsIndex--);32 }33 34 35 final int j = lastGreater(stack, a, heights);36 if (j != -1)37 ans[queryIndex] = stack.get(j);38 }39 }40 41 return ans;42 }43 44 private record IndexedQuery(int queryIndex, int a, int b){};45 46 47 private int lastGreater(List<Integer> A, int target, int[] heights) {48 int l = -1;49 int r = A.size() - 1;50 while (l < r) {51 final int m = (l + r + 1) / 2;52 if (heights[A.get(m)] > heights[target])53 l = m;54 else55 r = m - 1;56 }57 return l;58 }59 60 private IndexedQuery[] getIndexedQueries(int[][] queries) {61 IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];62 for (int i = 0; i < queries.length; ++i) {63 64 final int a = Math.min(queries[i][0], queries[i][1]);65 final int b = Math.max(queries[i][0], queries[i][1]);66 indexedQueries[i] = new IndexedQuery(i, a, b);67 }68 Arrays.sort(indexedQueries, Comparator.comparing(IndexedQuery::b, Comparator.reverseOrder()));69 return indexedQueries;70 }71}72