Taro Logo

Number of Flowers in Full Bloom

#148 Most AskedHard
0 views
Topics:
ArraysTwo PointersBinary Search

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.

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the maximum possible values for `start_i`, `end_i`, and elements in the `people` array? Also, what are the maximum sizes of the `flowers` and `people` arrays?
  2. Can the start day and end day of a flower be the same (i.e., `start_i == end_i`)? If so, is the flower considered to be in bloom only on that single day?
  3. Is it possible for the start day of a flower to be later than the end day (i.e., `start_i > end_i`)? If so, how should I handle such cases?
  4. If no flowers are in bloom for a particular person, should the corresponding element in the `answer` array be 0?
  5. Are the `flowers` ranges guaranteed to be non-overlapping, or can they overlap?

Brute Force Solution

Approach

Imagine you need to figure out how many flowers are blooming at specific moments in time by checking every single flower for every single moment. This brute force approach tests every possibility from scratch without taking any shortcuts.

Here's how the algorithm would work step-by-step:

  1. Take the first moment in time that someone asks about.
  2. Look at every single flower in the garden one by one.
  3. For each flower, check the calendar to see if it starts blooming on or before that moment and finishes on or after that moment.
  4. Count up how many flowers meet this condition.
  5. Write down that total count for the first moment.
  6. Move on to the next moment in time and repeat the entire counting process from the very beginning.
  7. Continue this process until you have checked every single flower for every single moment in time.

Code Implementation

def full_bloom_flowers(flowers, people):    # We store the final count for each queried arrival time to return at the end    bloom_count_results = []    # Iterate through every arrival time to evaluate flower coverage individually    for person_time in people:        current_flower_count = 0        for flower_interval in flowers:            start_bloom = flower_interval[0]            end_bloom = flower_interval[1]            if start_bloom <= person_time and person_time <= end_bloom:                current_flower_count += 1        bloom_count_results.append(current_flower_count)    # Return the accumulated counts matching the exact order of the people queries    return bloom_count_results

Big(O) Analysis

Time Complexity
O(m * n) – For each of the m moments in time queried by people, we iterate through every one of the n flowers in the garden to check if it is blooming. This means checking all n flowers for the first moment, all n flowers again for the second moment, and repeating this for every single moment. This leads to approximately m * n operations, which simplifies to O(m * n).
Space Complexity
O(n) – The brute force approach described in the explanation does not utilize any additional data structures beyond a few primitive integer variables to track the current moment and flower counts. Because we only iterate through the existing flowers and moments without storing intermediate results or recursion frames, the extra memory required remains constant. Therefore, the auxiliary space complexity is O(1) beyond the input arrays, or O(n) if we consider the output array required to store the count for each moment, where n is the number of queried moments.

Optimal Solution

Approach

Instead of checking every single flower's schedule one by one every time someone visits, the optimal approach organizes all the starting and ending times in order. By sorting these times, we can use a smart counting trick to quickly figure out how many flowers are blooming at any given moment.

Here's how the algorithm would work step-by-step:

  1. Gather all the exact times when flowers start blooming and put them in order from earliest to latest.
  2. Gather all the exact times when flowers stop blooming and put them in those same kinds of ordered lines.
  3. For any person who arrives to look at the flowers, look at the sorted start times to quickly figure out how many flowers have already started blooming by that exact moment.
  4. Then, look at the sorted stop times to figure out how many flowers have already finished blooming before that exact moment.
  5. Subtract the number of finished flowers from the number of started flowers to instantly find out how many are blooming right now.
  6. Repeat this quick lookup for every person who arrives without ever needing to inspect individual flowers one by one.

Code Implementation

import bisect


def full_bloom_flowers(flower_intervals, arrival_times):
    start_times = sorted([flower[0] for flower in flower_intervals])

    end_times = sorted([flower[1] for flower in flower_intervals])

    # Sorting allows binary search for fast lookups instead of checking every flower.
    bloom_results = []

    for arrival_time in arrival_times:
        started_count = bisect.bisect_right(start_times, arrival_time)

        # Find how many flowers started before or at this arrival time.
        finished_count = bisect.bisect_left(end_times, arrival_time)

        # Subtract finished from started to isolate the currently blooming flowers.
        active_flowers = started_count - finished_count

        bloom_results.append(active_flowers)

    return bloom_results

Big(O) Analysis

Time Complexity
O((n + m) log n) – Let n be the number of flowers and m be the number of people visiting. First, we extract and sort both the start times and end times of the flowers, which takes O(n log n) time. Then, for each of the m people, we perform two binary searches using upper_bound on these sorted arrays, taking O(m log n) time in total. Combining these sorting and searching steps yields approximately n log n + 2m log n operations, which simplifies to O((n + m) log n).
Space Complexity
O(n) – The auxiliary space is driven by two separate lists used to store the start times and the end times of the flowers. Letting N be the total number of flowers, we create a sorted array of size N for the start times and another sorted array of size N for the end times. Consequently, these extra data structures require memory proportional to the number of flowers. Simplifying this to Big O notation yields an overall auxiliary space complexity of O(N).

Edge Cases

Person arrival time falls completely outside the bloom range of all flowers
How to Handle:
Binary search returns zero for both start and end counts, resulting in a difference of zero.
Person arrives exactly on the start day or end day of a flower bloom
How to Handle:
Using upper_bound for start times and lower_bound for end times correctly includes boundary days since blooms are inclusive.
All flowers have the exact same bloom and fade times
How to Handle:
Sorting both start and end arrays correctly groups the identical values, allowing binary search to count them all accurately.
Extremely large constraints where flower times and arrival times reach up to 10 to the 9th power
How to Handle:
Using binary search on sorted arrays ensures an efficient logarithmic time complexity per query instead of a slow linear scan.
People arrive in completely unsorted order
How to Handle:
Storing original indices alongside arrival times allows us to sort the queries for processing and then restore the original order in the result array.
Multiple flowers start or end blooming at the exact same time
How to Handle:
Sorting the start and end time arrays allows binary search to correctly determine the exact number of active flowers regardless of duplicates.
The arrival times of people are completely outside the range of all flower bloom times, either all too early or all too late
How to Handle:
Binary search bounds will evaluate to zero active flowers, correctly outputting a list of zeros.
Maximum possible inputs causing potential integer overflow in languages with strict sizing
How to Handle:
Standard 32-bit signed integers are sufficient since constraints fit within standard limits, but using 64-bit integers prevents any overflow risks during sorting and indexing.
0/257 completed