Problem Description
Given an array of flowers where each flower is represented by a start and end time indicating when it is in full bloom, and given an array of people arrival times, determine for each person how many flowers are in full bloom at the moment they arrive.
Key Insights
- Instead of checking each flower for every person (which is inefficient), precompute and sort the start and end times of the flower intervals.
- For each person's arrival time, count how many flowers have started blooming using binary search on the sorted start times.
- Similarly, count how many flowers have finished blooming (end time less than the arrival time) using binary search on the sorted end times.
- The difference gives the number of flowers in full bloom at that time.
Space and Time Complexity
Time Complexity: O((n + m) log n) where n is the number of flowers and m is the number of people. Space Complexity: O(n) for storing sorted start and end time arrays.
Solution
We use a binary search approach for efficiency. First, extract and sort the start times and end times from the flowers array. For each person's arrival time, use binary search to:
- Find the count of flowers that have started blooming (using bisect_right or upper bound search on start times).
- Find the count of flowers that have ended before the arrival time (using bisect_left or lower bound search on end times). Subtracting the second count from the first yields the number of flowers still in full bloom. This solution efficiently handles large inputs under the given constraints.