Number of Flowers in Full Bloom

Hard Intervals Line Sweep

Number of Flowers in Full Bloom is a hard intervals problem solved with the line sweep pattern. The best approach, optimal (line sweep over people in time order), runs in O(n log n + m log m) time and O(n + m) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (check every flower for every person) up.

Problem

Each flower in a garden blooms for one stretch of time. You get a 2D array flowers, where flowers[i] = [start_i, end_i] means the i-th flower is in full bloom from time start_i to time end_i, including both ends.

You also get an array people, where people[i] is the time at which the i-th person arrives to look at the garden.

Return an array answer of the same length as people, where answer[i] is the number of flowers in full bloom at the moment the i-th person arrives.

Examples

Example 1

Input
flowers = [[1,4],[2,6],[5,8]], people = [1,3,5,9]
Output
[1,2,2,0]
Why
At time 1 only [1,4] is open. At time 3, [1,4] and [2,6] are open. At time 5, [1,4] has closed but [2,6] and [5,8] are open. At time 9 every flower has closed.

Example 2

Input
flowers = [[2,2],[2,5]], people = [2,3,1]
Output
[2,1,0]
Why
Both flowers are open at time 2, because a flower that opens and closes on the same day still counts on that day. At time 3 only [2,5] is left. Time 1 is before anything opens.

Example 3

Input
flowers = [[1,10]], people = [10,10,11]
Output
[1,1,0]
Why
The end time is inclusive, so the flower still counts at time 10. It is gone at time 11. Two people may arrive at the same time.

Constraints

  • 1 <= flowers.length <= 5 * 10^4
  • flowers[i].length == 2
  • 1 <= start_i <= end_i <= 10^9
  • 1 <= people.length <= 5 * 10^4
  • 1 <= people[i] <= 10^9

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (check every flower for every person)O(n · m)O(1)
Binary search on sorted starts and endsO((n + m) log n)O(n)
Optimal (line sweep over people in time order)O(n log n + m log m)O(n + m)

1Brute force (check every flower for every person)

TimeO(n · m)Each of the m people checks all n flowers.
SpaceO(1)Only a counter, apart from the answer array.

For each person, walk through all the flowers and count the ones whose bloom window contains that person's arrival time. It is a direct reading of the statement.

  1. Make an answer array the size of people.
  2. For each person i with arrival time t, set count = 0.
  3. For each flower [start, end], add one to count if start <= t and t <= end.
  4. Store count in answer[i].
class Solution {
    public int[] fullBloomFlowers(int[][] flowers, int[] people) {
        int[] answer = new int[people.length];
        for (int i = 0; i < people.length; i++) {
            int t = people[i], count = 0;
            for (int[] f : flowers)
                if (f[0] <= t && t <= f[1]) count++;
            answer[i] = count;
        }
        return answer;
    }
}

2Binary search on sorted starts and ends

TimeO((n + m) log n)Sorting the two arrays costs O(n log n), and each of the m people does two binary searches of O(log n).
SpaceO(n)The two sorted arrays of n times each.

A flower is in bloom at time t when it has started (start <= t) and has not yet ended (end >= t). Every flower that ended before t had also started before t, so the bloom count is simply (flowers with start <= t) minus (flowers with end < t). Sort the start times and the end times into two separate arrays. Each of the two counts is then one binary search: the number of values in a sorted array that are at most x.

  1. Copy all start times into starts and all end times into ends, then sort both.
  2. For each person with time t: started = how many starts are <= t.
  3. ended = how many ends are <= t - 1, that is, strictly before t.
  4. The answer for that person is started - ended.
  5. countAtMost(a, x) is a binary search for the first index whose value is greater than x.
class Solution {
    public int[] fullBloomFlowers(int[][] flowers, int[] people) {
        int n = flowers.length;
        int[] starts = new int[n], ends = new int[n];
        for (int i = 0; i < n; i++) {
            starts[i] = flowers[i][0];
            ends[i] = flowers[i][1];
        }
        Arrays.sort(starts);
        Arrays.sort(ends);
        int[] answer = new int[people.length];
        for (int i = 0; i < people.length; i++) {
            int t = people[i];
            int started = countAtMost(starts, t);
            int ended = countAtMost(ends, t - 1);
            answer[i] = started - ended;
        }
        return answer;
    }

    private int countAtMost(int[] a, int x) {
        int lo = 0, hi = a.length;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] <= x) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}

3Optimal (line sweep over people in time order)

TimeO(n log n + m log m)Sorting the starts, the ends and the people dominates. The sweep itself is O(n + m), because each pointer passes each flower once.
SpaceO(n + m)The two sorted time arrays and the order array of people indexes.

Use the same split, started minus ended, but replace the binary searches with two pointers that only move forward. Visit the people in order of arrival time, without moving them: sort a list of their indexes by time. As time moves forward, pointer s counts the starts that are <= t and pointer e counts the ends that are < t. Neither pointer ever moves back, so all the people together cost one pass over each sorted array. The answer goes into the person's original index.

  1. Sort the start times and the end times into two arrays, as before.
  2. Make order = the indexes 0..m-1, sorted by people[index].
  3. s = 0, e = 0. For each index in order, with t = people[index]:
  4. While s < n and starts[s] <= t, move s forward. While e < n and ends[e] < t, move e forward.
  5. answer[index] = s - e: flowers started so far minus flowers already finished.
class Solution {
    public int[] fullBloomFlowers(int[][] flowers, int[] people) {
        int n = flowers.length, m = people.length;
        int[] starts = new int[n], ends = new int[n];
        for (int i = 0; i < n; i++) {
            starts[i] = flowers[i][0];
            ends[i] = flowers[i][1];
        }
        Arrays.sort(starts);
        Arrays.sort(ends);
        Integer[] order = new Integer[m];
        for (int i = 0; i < m; i++) order[i] = i;
        Arrays.sort(order, (a, b) -> Integer.compare(people[a], people[b]));
        int[] answer = new int[m];
        int s = 0, e = 0;
        for (int idx : order) {
            int t = people[idx];
            while (s < n && starts[s] <= t) s++;
            while (e < n && ends[e] < t) e++;
            answer[idx] = s - e;
        }
        return answer;
    }
}

Edge cases to test

  • A person arrives exactly on a start time or exactly on an end time: both count, since the bloom is inclusive at both ends
  • A flower whose start equals its end blooms for a single moment
  • A person arrives before every flower opens or after every flower closes (answer 0)
  • Several people arrive at the same time, or people are not in sorted order: answers must go back to their original positions
  • Times go up to 10^9, so an array indexed by time is far too large
  • Many flowers share the same start or end time

Hints

Hint 1

For one arrival time t, a flower counts when start <= t and t <= end. Checking every flower for every person works but is slow.

Hint 2

Split the count: flowers that have opened by time t, minus flowers that have already closed before time t. A flower that closed before t certainly opened before t.

Hint 3

Sort all start times and all end times separately. The number of starts <= t and the number of ends < t are each one binary search, or one moving pointer if you visit people in time order.

FAQ

What is the best time complexity for Number of Flowers in Full Bloom?

Optimal (line sweep over people in time order) runs in O(n log n + m log m) time and O(n + m) extra space. Sorting the starts, the ends and the people dominates. The sweep itself is O(n + m), because each pointer passes each flower once.

Which pattern does Number of Flowers in Full Bloom use?

It is a intervals problem that uses the line sweep pattern. Other problems with the same pattern: Meeting Rooms II, Car Pooling, Employee Free Time.

Is there a brute force solution for Number of Flowers in Full Bloom?

Yes. Brute force (check every flower for every person) takes O(n · m) time and O(1) space. For each person, walk through all the flowers and count the ones whose bloom window contains that person's arrival time.

Which edge cases should I test for Number of Flowers in Full Bloom?

A person arrives exactly on a start time or exactly on an end time: both count, since the bloom is inclusive at both ends; A flower whose start equals its end blooms for a single moment; A person arrives before every flower opens or after every flower closes (answer 0); Several people arrive at the same time, or people are not in sorted order: answers must go back to their original positions; Times go up to 10^9, so an array indexed by time is far too large; Many flowers share the same start or end time.