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
startandendtimes 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
starttimes). - Count the flowers that have already finished blooming before the arrival time (using
endtimes).
- 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
startandendarrays 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
startsandendsarrays:O(m log m)wheremis the number of flowers. - Querying each
pwith binary search in sorted arrays:O(n log m)wherenis the number of people.
- Sorting
- 🧺 Space complexity:
O(m + n)O(m)forstarts,endsarrays.O(n)foransresult array.- Total:
O(m + n).