Number of Flowers in Full Bloom
Number of Flowers in Full Bloom is a hard intervals problem solved with the line sweep pattern.
The best approach, optimal (line sweep over people in time order), runs in O(n log n + m log m) time and O(n + m) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (check every flower for every person) up.
Problem
Each flower in a garden blooms for one stretch of time. You get a 2D array flowers, where flowers[i] = [start_i, end_i] means the i-th flower is in full bloom from time start_i to time end_i, including both ends.
You also get an array people, where people[i] is the time at which the i-th person arrives to look at the garden.
Return an array answer of the same length as people, where answer[i] is the number of flowers in full bloom at the moment the i-th person arrives.
Examples
Example 1
- Input
flowers = [[1,4],[2,6],[5,8]], people = [1,3,5,9]- Output
[1,2,2,0]- Why
- At time 1 only [1,4] is open. At time 3, [1,4] and [2,6] are open. At time 5, [1,4] has closed but [2,6] and [5,8] are open. At time 9 every flower has closed.
Example 2
- Input
flowers = [[2,2],[2,5]], people = [2,3,1]- Output
[2,1,0]- Why
- Both flowers are open at time 2, because a flower that opens and closes on the same day still counts on that day. At time 3 only [2,5] is left. Time 1 is before anything opens.
Example 3
- Input
flowers = [[1,10]], people = [10,10,11]- Output
[1,1,0]- Why
- The end time is inclusive, so the flower still counts at time 10. It is gone at time 11. Two people may arrive at the same time.
Constraints
1 <= flowers.length <= 5 * 10^4flowers[i].length == 21 <= start_i <= end_i <= 10^91 <= people.length <= 5 * 10^41 <= people[i] <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (check every flower for every person) | O(n · m) | O(1) |
| Binary search on sorted starts and ends | O((n + m) log n) | O(n) |
| Optimal (line sweep over people in time order) | O(n log n + m log m) | O(n + m) |
1Brute force (check every flower for every person)
O(n · m)Each of the m people checks all n flowers.O(1)Only a counter, apart from the answer array.For each person, walk through all the flowers and count the ones whose bloom window contains that person's arrival time. It is a direct reading of the statement.
- Make an answer array the size of people.
- For each person i with arrival time t, set count = 0.
- For each flower [start, end], add one to count if start <= t and t <= end.
- Store count in answer[i].
class Solution {
public int[] fullBloomFlowers(int[][] flowers, int[] people) {
int[] answer = new int[people.length];
for (int i = 0; i < people.length; i++) {
int t = people[i], count = 0;
for (int[] f : flowers)
if (f[0] <= t && t <= f[1]) count++;
answer[i] = count;
}
return answer;
}
}class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:
answer = [0] * len(people)
for i, t in enumerate(people):
count = 0
for start, end in flowers:
if start <= t <= end:
count += 1
answer[i] = count
return answerclass Solution {
public:
vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& people) {
vector<int> answer(people.size());
for (int i = 0; i < (int)people.size(); i++) {
int t = people[i], count = 0;
for (auto& f : flowers)
if (f[0] <= t && t <= f[1]) count++;
answer[i] = count;
}
return answer;
}
};function fullBloomFlowers(flowers, people) {
const answer = new Array(people.length).fill(0);
for (let i = 0; i < people.length; i++) {
const t = people[i];
let count = 0;
for (const f of flowers)
if (f[0] <= t && t <= f[1]) count++;
answer[i] = count;
}
return answer;
}2Binary search on sorted starts and ends
O((n + m) log n)Sorting the two arrays costs O(n log n), and each of the m people does two binary searches of O(log n).O(n)The two sorted arrays of n times each.A flower is in bloom at time t when it has started (start <= t) and has not yet ended (end >= t). Every flower that ended before t had also started before t, so the bloom count is simply (flowers with start <= t) minus (flowers with end < t). Sort the start times and the end times into two separate arrays. Each of the two counts is then one binary search: the number of values in a sorted array that are at most x.
- Copy all start times into starts and all end times into ends, then sort both.
- For each person with time t: started = how many starts are <= t.
- ended = how many ends are <= t - 1, that is, strictly before t.
- The answer for that person is started - ended.
- countAtMost(a, x) is a binary search for the first index whose value is greater than x.
class Solution {
public int[] fullBloomFlowers(int[][] flowers, int[] people) {
int n = flowers.length;
int[] starts = new int[n], ends = new int[n];
for (int i = 0; i < n; i++) {
starts[i] = flowers[i][0];
ends[i] = flowers[i][1];
}
Arrays.sort(starts);
Arrays.sort(ends);
int[] answer = new int[people.length];
for (int i = 0; i < people.length; i++) {
int t = people[i];
int started = countAtMost(starts, t);
int ended = countAtMost(ends, t - 1);
answer[i] = started - ended;
}
return answer;
}
private int countAtMost(int[] a, int x) {
int lo = 0, hi = a.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] <= x) lo = mid + 1;
else hi = mid;
}
return lo;
}
}class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:
starts = sorted(f[0] for f in flowers)
ends = sorted(f[1] for f in flowers)
answer = [0] * len(people)
for i, t in enumerate(people):
started = self.countAtMost(starts, t)
ended = self.countAtMost(ends, t - 1)
answer[i] = started - ended
return answer
def countAtMost(self, a: List[int], x: int) -> int:
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] <= x:
lo = mid + 1
else:
hi = mid
return loclass Solution {
public:
vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& people) {
int n = flowers.size();
vector<int> starts(n), ends(n);
for (int i = 0; i < n; i++) {
starts[i] = flowers[i][0];
ends[i] = flowers[i][1];
}
sort(starts.begin(), starts.end());
sort(ends.begin(), ends.end());
vector<int> answer(people.size());
for (int i = 0; i < (int)people.size(); i++) {
int t = people[i];
int started = countAtMost(starts, t);
int ended = countAtMost(ends, t - 1);
answer[i] = started - ended;
}
return answer;
}
private:
int countAtMost(vector<int>& a, int x) {
int lo = 0, hi = a.size();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] <= x) lo = mid + 1;
else hi = mid;
}
return lo;
}
};function fullBloomFlowers(flowers, people) {
const n = flowers.length;
const starts = new Array(n), ends = new Array(n);
for (let i = 0; i < n; i++) {
starts[i] = flowers[i][0];
ends[i] = flowers[i][1];
}
starts.sort((a, b) => a - b);
ends.sort((a, b) => a - b);
const answer = new Array(people.length).fill(0);
for (let i = 0; i < people.length; i++) {
const t = people[i];
const started = countAtMost(starts, t);
const ended = countAtMost(ends, t - 1);
answer[i] = started - ended;
}
return answer;
}
function countAtMost(a, x) {
let lo = 0, hi = a.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (a[mid] <= x) lo = mid + 1;
else hi = mid;
}
return lo;
}3Optimal (line sweep over people in time order)
O(n log n + m log m)Sorting the starts, the ends and the people dominates. The sweep itself is O(n + m), because each pointer passes each flower once.O(n + m)The two sorted time arrays and the order array of people indexes.Use the same split, started minus ended, but replace the binary searches with two pointers that only move forward. Visit the people in order of arrival time, without moving them: sort a list of their indexes by time. As time moves forward, pointer s counts the starts that are <= t and pointer e counts the ends that are < t. Neither pointer ever moves back, so all the people together cost one pass over each sorted array. The answer goes into the person's original index.
- Sort the start times and the end times into two arrays, as before.
- Make order = the indexes 0..m-1, sorted by people[index].
- s = 0, e = 0. For each index in order, with t = people[index]:
- While s < n and starts[s] <= t, move s forward. While e < n and ends[e] < t, move e forward.
- answer[index] = s - e: flowers started so far minus flowers already finished.
class Solution {
public int[] fullBloomFlowers(int[][] flowers, int[] people) {
int n = flowers.length, m = people.length;
int[] starts = new int[n], ends = new int[n];
for (int i = 0; i < n; i++) {
starts[i] = flowers[i][0];
ends[i] = flowers[i][1];
}
Arrays.sort(starts);
Arrays.sort(ends);
Integer[] order = new Integer[m];
for (int i = 0; i < m; i++) order[i] = i;
Arrays.sort(order, (a, b) -> Integer.compare(people[a], people[b]));
int[] answer = new int[m];
int s = 0, e = 0;
for (int idx : order) {
int t = people[idx];
while (s < n && starts[s] <= t) s++;
while (e < n && ends[e] < t) e++;
answer[idx] = s - e;
}
return answer;
}
}class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:
n, m = len(flowers), len(people)
starts = sorted(f[0] for f in flowers)
ends = sorted(f[1] for f in flowers)
order = sorted(range(m), key=lambda i: people[i])
answer = [0] * m
s = e = 0
for idx in order:
t = people[idx]
while s < n and starts[s] <= t:
s += 1
while e < n and ends[e] < t:
e += 1
answer[idx] = s - e
return answerclass Solution {
public:
vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& people) {
int n = flowers.size(), m = people.size();
vector<int> starts(n), ends(n);
for (int i = 0; i < n; i++) {
starts[i] = flowers[i][0];
ends[i] = flowers[i][1];
}
sort(starts.begin(), starts.end());
sort(ends.begin(), ends.end());
vector<int> order(m);
for (int i = 0; i < m; i++) order[i] = i;
sort(order.begin(), order.end(), [&](int a, int b) { return people[a] < people[b]; });
vector<int> answer(m);
int s = 0, e = 0;
for (int idx : order) {
int t = people[idx];
while (s < n && starts[s] <= t) s++;
while (e < n && ends[e] < t) e++;
answer[idx] = s - e;
}
return answer;
}
};function fullBloomFlowers(flowers, people) {
const n = flowers.length, m = people.length;
const starts = flowers.map((f) => f[0]).sort((a, b) => a - b);
const ends = flowers.map((f) => f[1]).sort((a, b) => a - b);
const order = [...Array(m).keys()].sort((a, b) => people[a] - people[b]);
const answer = new Array(m).fill(0);
let s = 0, e = 0;
for (const idx of order) {
const t = people[idx];
while (s < n && starts[s] <= t) s++;
while (e < n && ends[e] < t) e++;
answer[idx] = s - e;
}
return answer;
}Edge cases to test
- A person arrives exactly on a start time or exactly on an end time: both count, since the bloom is inclusive at both ends
- A flower whose start equals its end blooms for a single moment
- A person arrives before every flower opens or after every flower closes (answer 0)
- Several people arrive at the same time, or people are not in sorted order: answers must go back to their original positions
- Times go up to 10^9, so an array indexed by time is far too large
- Many flowers share the same start or end time
Hints
Hint 1
For one arrival time t, a flower counts when start <= t and t <= end. Checking every flower for every person works but is slow.
Hint 2
Split the count: flowers that have opened by time t, minus flowers that have already closed before time t. A flower that closed before t certainly opened before t.
Hint 3
Sort all start times and all end times separately. The number of starts <= t and the number of ends < t are each one binary search, or one moving pointer if you visit people in time order.
FAQ
What is the best time complexity for Number of Flowers in Full Bloom?
Optimal (line sweep over people in time order) runs in O(n log n + m log m) time and O(n + m) extra space. Sorting the starts, the ends and the people dominates. The sweep itself is O(n + m), because each pointer passes each flower once.
Which pattern does Number of Flowers in Full Bloom use?
It is a intervals problem that uses the line sweep pattern. Other problems with the same pattern: Meeting Rooms II, Car Pooling, Employee Free Time.
Is there a brute force solution for Number of Flowers in Full Bloom?
Yes. Brute force (check every flower for every person) takes O(n · m) time and O(1) space. For each person, walk through all the flowers and count the ones whose bloom window contains that person's arrival time.
Which edge cases should I test for Number of Flowers in Full Bloom?
A person arrives exactly on a start time or exactly on an end time: both count, since the bloom is inclusive at both ends; A flower whose start equals its end blooms for a single moment; A person arrives before every flower opens or after every flower closes (answer 0); Several people arrive at the same time, or people are not in sorted order: answers must go back to their original positions; Times go up to 10^9, so an array indexed by time is far too large; Many flowers share the same start or end time.