- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 50 lines of Java from the credited upstream file 2251.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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[] fullBloomFlowers(int[][] flowers, int[] persons) {3 int[] ans = new int[persons.length];4 List<Integer> starts = new ArrayList<>();5 List<Integer> ends = new ArrayList<>();6 7 for (int[] flower : flowers) {8 starts.add(flower[0]);9 ends.add(flower[1]);10 }11 12 Collections.sort(starts);13 Collections.sort(ends);14 15 for (int i = 0; i < persons.length; ++i) {16 final int started = firstGreater(starts, persons[i]);17 final int ended = firstGreaterEqual(ends, persons[i]);18 ans[i] = started - ended;19 }20 21 return ans;22 }23 24 private int firstGreater(List<Integer> arr, int target) {25 int l = 0;26 int r = arr.size();27 while (l < r) {28 final int m = (l + r) / 2;29 if (arr.get(m) > target)30 r = m;31 else32 l = m + 1;33 }34 return l;35 }36 37 private int firstGreaterEqual(List<Integer> arr, int target) {38 int l = 0;39 int r = arr.size();40 while (l < r) {41 final int m = (l + r) / 2;42 if (arr.get(m) >= target)43 r = m;44 else45 l = m + 1;46 }47 return l;48 }49}50