#2251
Number of Flowers in Full Bloom
HardArrayHash TableBinary SearchSortingPrefix SumOrdered SetBinary SearchSortingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + m log n)Space O(n)
We can efficiently count blooming flowers using sorting and binary search. By creating two separate lists for start and end times, we can quickly determine how many flowers are blooming at any given time.
⚙️
Algorithm
3 steps- 1Step 1: Create two lists, one for start times and one for end times, and sort both.
- 2Step 2: For each person's arrival time, use binary search to find how many flowers have started blooming and how many have stopped blooming by that time.
- 3Step 3: The difference between the two counts gives the number of flowers blooming at that time.
solution.py8 lines
1def numFlowersInBloom(flowers, people):
2 starts = sorted(start for start, end in flowers)
3 ends = sorted(end for start, end in flowers)
4 result = []
5 for person in people:
6 blooming = bisect.bisect_right(starts, person) - bisect.bisect_left(ends, person)
7 result.append(blooming)
8 return resultℹ
Complexity note: Sorting the start and end times takes O(n log n), and each query for a person takes O(log n) due to binary search, leading to a total of O(n log n + m log n).
- 1Understanding the blooming period as a range helps in counting efficiently.
- 2Using sorting and binary search can significantly reduce the time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.