Minimum Number of Days to Make m Bouquets (LeetCode 1482): Solution and Explanation

Medium
Array
Binary Search

Flower i opens on day bloomDay[i]. A bouquet takes k adjacent open flowers. Return the earliest day on which m bouquets can be made, or -1 if that never happens.

Intuition

First check whether the garden is big enough at all. Every bouquet uses k flowers and no flower is reused, so m bouquets need m * k flowers. If that is more than n, return -1 right away.

Otherwise waiting until the last flower opens always works, because then the whole row is open and you can cut it into consecutive groups of k. And a flower never closes again, so if day d is enough, every later day is enough too. The answer is the first day where a yes/no test flips from no to yes.

That test is easy for one fixed day: walk the row, count how many open flowers you have seen in a row, and whenever that count reaches k, tie a bouquet and start counting again. Taking the leftmost k flowers greedily never hurts, because leaving a gap cannot create more room on the right.

Binary search the day between the earliest and latest bloom, running the walk once per guess.

Approach: Binary search on the day with a greedy run counter

  1. If m * k > len(bloomDay), return -1.
  2. Set lo = min(bloomDay) and hi = max(bloomDay). hi always holds a day known to work.
  3. While lo < hi, take mid = (lo + hi) // 2. Walk the garden with run and bouquets: an open flower (day <= mid) adds 1 to run, a closed one resets it to 0, and run == k adds a bouquet and resets run.
  4. If bouquets >= m, set hi = mid; otherwise set lo = mid + 1.
  5. Return lo.

Step-by-step example

bloomDay = [1,10,3,10,2], m = 3, k = 1
  1. m * k = 3 <= 5 flowers, so an answer exists. Range [1, 10].
  2. mid = 5: open flowers are at indices 0, 2 and 4. With k = 1 each one is a bouquet, 3 >= 3. hi = 5.
  3. mid = 3: indices 0, 2 and 4 are still open (days 1, 3, 2). 3 bouquets. hi = 3.
  4. mid = 2: only indices 0 and 4 are open. 2 < 3 bouquets. lo = 3.
  5. lo = hi = 3, so the answer is day 3.

Code: Python, Java, C++

1class Solution:
2    def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
3        if m * k > len(bloomDay):
4            return -1
5        lo, hi = min(bloomDay), max(bloomDay)
6        while lo < hi:
7            mid = (lo + hi) // 2
8            bouquets = run = 0
9            for day in bloomDay:
10                run = run + 1 if day <= mid else 0
11                if run == k:
12                    bouquets += 1
13                    run = 0
14            if bouquets >= m:
15                hi = mid
16            else:
17                lo = mid + 1
18        return lo
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log D)

D is max(bloomDay), up to 10^9, so the binary search takes about 30 rounds, each one a single pass over the n flowers.

Space

O(1)

Only lo, hi, mid, run and bouquets are stored.

Other approaches

Binary search over the sorted distinct bloom days (time O(n log n), space O(n))

The answer is always one of the bloom days, so sort the distinct values and binary search their indices. Same idea, slightly fewer rounds, plus an O(n log n) sort.

Try every distinct bloom day in order (time O(n^2), space O(n))

Sort the distinct days and test them from earliest to latest until one works. Simple, but up to n tests of O(n) each.

Common mistakes

  • Computing m * k in 32-bit ints. m can be 10^6 and k can be 10^5, so the product overflows; cast to long first.
  • Forgetting to reset the run after a bouquet. The flowers just used cannot be counted again for the next bouquet.
  • Counting all open flowers instead of adjacent ones. Open flowers separated by a bud cannot share a bouquet.
  • Searching from day 0 or day 1 instead of min(bloomDay). It still works but wastes rounds; searching up to 10^9 instead of max(bloomDay) is also fine but unnecessary.

Frequently asked questions

Why is taking the first k open flowers in a run always safe?

Any bouquet that starts further right inside the same run leaves the flowers on its left unused and pushes the next bouquet even further right. Starting as early as possible leaves the most room after it, so greedy never makes fewer bouquets.

Why can lo start at min(bloomDay)?

Before the first flower opens nothing is open, and m is at least 1, so no earlier day can work.

Is the answer always one of the bloom days?

Yes. Between two consecutive bloom days nothing changes in the garden, so the first working day is the day some flower opens. The binary search finds it without needing that fact.

How does this compare to Koko Eating Bananas?

Both binary search a value whose feasibility is monotone. Here the check walks the array counting runs; in Koko it sums rounded-up quotients.