Sponsored
Sponsored
This approach involves sorting the start and end times of the flowers separately. For each person’s arrival time, we use binary search to determine how many flowers have started blooming and how many have stopped. The difference will give us the number of flowers in full bloom.
Time Complexity: O((m + n) log m), where m is the number of flowers and n is the number of people.
Space Complexity: O(m), since we store the start and end times separately.
1from bisect import bisect_right, bisect_left
2
3def numberOfFlowersInFullBloom(flowers, people):
4 start_times = sorted([start for start, _ in flowers])
5 end_times = sorted([end for _, end in flowers])
6 result = []
7 for time in people:
8 start_count = bisect_right(start_times, time)
9 end_count = bisect_left(end_times, time)
10 result.append(start_count - end_count)
11 return result
12
13# Example usage:
14flowers = [[1,6],[3,7],[9,12],[4,13]]
15people = [2,3,7,11]
16print(numberOfFlowersInFullBloom(flowers, people))
In this implementation, we first extract and sort the start and end times separately. When iterating over each person's arrival time, we use bisect_right
to count how many flowers have started to bloom by that time and bisect_left
to count how many flowers have finished blooming by that time. The difference gives the number of flowers that are blooming.
This approach optimizes the flower counting by utilizing a two-pointer method after sorting both the start and end times, as well as people’s arrival times. This helps reduce unnecessary recomputation and simplifies the logic.
Time Complexity: O(m log m + n log n), where m is the number of flowers and n is the number of people, containing costs for sorting and linear traversal.
Space Complexity: O(m + n), for holding sorted intervals and the result array.
1function numberOfFlowersInFullBloom(flowers, people) {
2 const starts = flowers.map
This JavaScript solution employs the two-pointer technique to traverse sorted start and end times while adjusting the count of currently blooming flowers. The people’s arrival times are first mapped to their original indices and sorted, ensuring the results are recorded in the correct order.