Problem
You are given a 0-indexed 2D integer array flowers
, where flowers[i] = [starti, endi]
means the ith
flower will be in full bloom from starti
to endi
(inclusive). You are also given a 0-indexed integer array people
of size n
, where people[i]
is the time that the ith
person will arrive to see the flowers.
Return an integer array answer
of size n
, where answer[i]
is the number of flowers that are in full bloom when the ith
person arrives.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using Binary Search
The problem involves determining for each person, how many flowers are in full bloom at the given time they arrive. We approach this efficiently instead of checking each person’s arrival time against every interval of bloom directly, which can be computationally expensive.
Approach
- Separate the
start
andend
times of flowers into two sorted arrays. - For each person’s arrival time (
people[i]
), use binary search to:- Count the number of flowers that have started blooming up to the arrival time (using
start
times). - Count the flowers that have already finished blooming before the arrival time (using
end
times).
- Count the number of flowers that have started blooming up to the arrival time (using
- Subtract the count of flowers that have ended from those that have started blooming to determine the number of flowers in bloom at the given arrival time.
- Sorting both
start
andend
arrays enables efficient queries using binary search. - The use of binary search reduces the time complexity compared to brute force iteration.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m log m + n log m)
.- Sorting
starts
andends
arrays:O(m log m)
wherem
is the number of flowers. - Querying each
p
with binary search in sorted arrays:O(n log m)
wheren
is the number of people.
- Sorting
- 🧺 Space complexity:
O(m + n)
O(m)
forstarts
,ends
arrays.O(n)
forans
result array.- Total:
O(m + n)
.