- 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
- 30 lines of Java from the credited upstream file 2055.java.
- The implementation visibly relies on sequence storage.
- 2 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 public int[] platesBetweenCandles(String s, int[][] queries) {3 int[] ans = new int[queries.length];4 List<Integer> indices = new ArrayList<>(); 5 6 for (int i = 0; i < s.length(); ++i)7 if (s.charAt(i) == '|')8 indices.add(i);9 10 for (int i = 0; i < queries.length; ++i) {11 final int left = queries[i][0];12 final int right = queries[i][1];13 final int l = firstGreaterEqual(indices, left);14 final int r = firstGreaterEqual(indices, right + 1) - 1;15 if (l < r) {16 final int lengthBetweenCandles = indices.get(r) - indices.get(l) + 1;17 final int numCandles = r - l + 1;18 ans[i] = lengthBetweenCandles - numCandles;19 }20 }21 22 return ans;23 }24 25 private int firstGreaterEqual(List<Integer> indices, int target) {26 final int i = Collections.binarySearch(indices, target);27 return i < 0 ? -i - 1 : i;28 }29}30