Number of Flowers in Full Bloom

For each query time, count blooming flowers using two sorted endpoint arrays and binary search.

Hard
Time O((n + q) log n) Space O(n)
LeetCode
5 min read
binary-search sorting

Problem#

flowers[i] = [start, end] (inclusive). For each q in queries, return the count of flowers blooming at time q.

Examples#

  • flowers = [[1,6],[3,7],[9,12],[4,13]], queries = [2,3,7,11][1,2,2,2]

Constraints#

  • 1 <= flowers.length, queries.length <= 5 * 10^4.

Hints#

Hint 1
Blooming at time q = (#starts ≤ q) − (#ends < q). Both counts are upper/lower bounds on sorted endpoint arrays.

Approach#

Two sorted arrays: starts (ascending) and ends (ascending). For each query q, answer is (upper_bound(starts, q) - starts.begin()) - (lower_bound(ends, q) - ends.begin()).

Solution#

Number of Flowers in Full Bloom
class Solution {
public:
vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& queries) {
vector<int> starts, ends;
starts.reserve(flowers.size()); ends.reserve(flowers.size());
for (auto& f : flowers) { starts.push_back(f[0]); ends.push_back(f[1]); }
sort(starts.begin(), starts.end());
sort(ends.begin(), ends.end());
vector<int> ans;
ans.reserve(queries.size());
for (int q : queries) {
int started = upper_bound(starts.begin(), starts.end(), q) - starts.begin();
int ended = lower_bound(ends.begin(), ends.end(), q) - ends.begin();
ans.push_back(started - ended);
}
return ans;
}
};

Editorial#

Decoupling start and end times into independent sorted arrays is the classical event-counting trick. upper_bound(starts, q) counts how many start <= q (already started); lower_bound(ends, q) counts how many end < q (already ended). The difference is currently blooming.

Complexity#

  • Time: O((n + q) log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.