
Problem Statement
In this problem, you are provided with two primary pieces of data in the form of 0-indexed arrays. The first is a 2D array named flowers
, where each sub-array flowers[i]
contains two integers [starti, endi]
representing the time frame (inclusive) during which the i-th
flower is in full bloom. The second array, people
, is a 1D integer array where each element people[i]
denotes the time point when the i-th
person arrives to view the flowers.
Your task is to determine how many flowers are in full bloom at the moment each person arrives. The result should be a new integer array answer
of size n
(where n
is the number of people), with each entry answer[i]
indicating the count of flowers in full bloom during people[i]'s
arrival.
Examples
Example 1
Input:
flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11]
Output:
[1,2,2,2]
Explanation:
The figure above shows the times when the flowers are in full bloom and when the people arrive. For each person, we return the number of flowers in full bloom during their arrival.
Example 2
Input:
flowers = [[1,10],[3,3]], people = [3,3,2]
Output:
[2,2,1]
Explanation:
The figure above shows the times when the flowers are in full bloom and when the people arrive. For each person, we return the number of flowers in full bloom during their arrival.
Constraints
1 <= flowers.length <= 5 * 104
flowers[i].length == 2
1 <= starti <= endi <= 109
1 <= people.length <= 5 * 104
1 <= people[i] <= 109
Approach and Intuition
To solve this problem, one feasible approach is iterating through each time people[i]
arrives and calculate how many flowers are blooming at that time. This naive approach has a complexity that might be too high for larger inputs, as it involves a nested iteration over both people
and flowers
.
Optimized Steps to Solve:
Sorting for Efficiency:
Start by sorting bothflowers
andpeople
arrays. Sorting can help facilitate more efficient searching techniques like binary search.Using Sweep Line Algorithm:
- Create a list of events from the
flowers
array. For each flower with interval[starti, endi]
, add an event atstarti
to increment bloom count and an event atendi + 1
to decrement it. - Sort these events. If two events have the same time, ensure increments occur before decrements.
- Create a list of events from the
Complexity Handling:
- As you process these events in time order, maintain a count of "currently blooming flowers". Increment or decrement this count based on event type.
- For each person in the sorted
people
list, calculate how many flowers are bloomed when they arrive using the precomputed bloom data from the events.
This approach leverages sorting and a sweeping technique to handle the updates and queries in a time complexity better suited for inputs near the upper limits of given constraints. Along with a more controlled space usage, this method efficiently answers the problem without directly comparing each person against all intervals.
Solutions
- C++
class Solution {
public:
vector<int> countFlowersInBloom(vector<vector<int>>& bloomPeriods, vector<int>& persons) {
vector<int> startTime;
vector<int> endTime;
for (vector<int>& bloom : bloomPeriods) {
startTime.push_back(bloom[0]);
endTime.push_back(bloom[1] + 1);
}
sort(startTime.begin(), startTime.end());
sort(endTime.begin(), endTime.end());
vector<int> result;
for (int person : persons) {
int startCount = upper_bound(startTime.begin(), startTime.end(), person) - startTime.begin();
int endCount = upper_bound(endTime.begin(), endTime.end(), person) - endTime.begin();
result.push_back(startCount - endCount);
}
return result;
}
};
The solution to the problem "Number of Flowers in Full Bloom" involves calculating how many flowers are blooming at the times queried by each person. The solution uses C++ for its implementation. The main idea is to employ sorting and binary search techniques to efficiently count the number of blooms for each query time.
Here's a breakdown of the solution:
- Extract start and end times of blooming periods into separate vectors, adjusting the end time by adding one to account for the inclusive nature of the blooming period end.
- Sort both the start and end time vectors. This sorting is crucial as it enables the use of binary search techniques.
- For each person's query time, determine how many blooms have started and not yet ended using
std::upper_bound
. Theupper_bound
function is leveraged here to find the first element in the sorted list that is greater than the queried time, which provides a count of blooms up to that point. - The difference between the counts from the start and end times vectors gives the number of flowers in bloom at the person’s specific time.
- Results are aggregated and returned.
This approach is efficient with respect to time complexity due to the use of sorting and binary search, both of which are significantly faster for large input sizes compared to naive comparisons. This makes the solution well-suited for scenarios where there are many queries and bloom periods to process.
- Java
class Solution {
public int[] evaluateFlowersStatus(int[][] flowers, int[] visitors) {
List<Integer> beginTimes = new ArrayList();
List<Integer> endTimes = new ArrayList();
for (int[] flower: flowers) {
beginTimes.add(flower[0]);
endTimes.add(flower[1] + 1);
}
Collections.sort(beginTimes);
Collections.sort(endTimes);
int[] result = new int[visitors.length];
for (int idx = 0; idx < visitors.length; idx++) {
int visitorTime = visitors[idx];
int startCount = customBinarySearch(beginTimes, visitorTime);
int endCount = customBinarySearch(endTimes, visitorTime);
result[idx] = startCount - endCount;
}
return result;
}
public int customBinarySearch(List<Integer> sortedList, int targetTime) {
int low = 0;
int high = sortedList.size();
while (low < high) {
int mid = (low + high) / 2;
if (targetTime < sortedList.get(mid)) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
}
The solution provided in Java tackles the problem of determining how many flowers are in full bloom at given times. The task is managed with the following steps:
Initialize two lists,
beginTimes
andendTimes
, to store the start and end times of flower blooming periods respectively. The end time is adjusted to (flower[1] + 1
) to handle the inclusion of end time in the blooming period.Populate these lists with the respective times from the
flowers
array and then sort both lists to facilitate efficient searching.Prepare an array
result
to store the count of flowers in full bloom at each visitor's time.Implement a
customBinarySearch
method tailored to find the position where the visitor’s time would fit into thebeginTimes
andendTimes
lists, helping determine how many flowers start blooming before or at the visitor's time and how many stop blooming just before the visitor's time. This method efficiently finds the correct count using binary search logic.For each time in the
visitors
array, calculate the difference between the count of flowers that have started to bloom and those that have ceased blooming by the respective times. This difference gives the number of flowers in full bloom at each visitor's time.Return the
result
array containing counts of flowers in bloom for all visitor times as determined by the successive computation and search steps.
The overall approach leverages efficient sorting and binary search techniques to make the solution capable of handling larger sets of data effectively.
- Python
class Solution:
def flowersInBloom(self, bloom_periods: List[List[int]], queries: List[int]) -> List[int]:
opening = []
closing = []
for open_time, close_time in bloom_periods:
opening.append(open_time)
closing.append(close_time + 1)
opening.sort()
closing.sort()
results = []
for query in queries:
start_idx = bisect_right(opening, query)
end_idx = bisect_right(closing, query)
results.append(start_idx - end_idx)
return results
In this solution to the "Number of Flowers in Full Bloom" problem, the code efficiently determines how many flowers are in bloom at each queried time. It uses a powerful approach leveraging sorting and binary search mechanisms in Python3. Here's a quick breakdown of how the provided solution works:
- Create lists to track when flowers start blooming (
opening
) and when they stop blooming (closing
). - Separate the bloom periods into open and close events, making a note to adjust the closing time to accommodate checks exclusive of the endpoint.
- Sort both
opening
andclosing
lists to enable efficient search operations. - Process each query time to count how many flowers are in bloom by determining:
- how many blooms have started (using
bisect_right
onopening
) - how many blooms have ended (using
bisect_right
onclosing
)
- how many blooms have started (using
- Calculate the difference between started blooms and ended blooms for each query to get the count of flowers in full bloom at that quarried moment.
This elegant solution ensures that you get accurate results with improved efficiency, crucial for handling a large set of data or queries without increasing computational load significantly.
No comments yet.