Minimum Number of Days to Make m Bouquets — LeetCode 1482 Python Solution

MediumArrayBinary Search
Problem
#1482
Reading time
3 min

The problem

You are given an integer array bloomDay, an integer m and an integer k. You want to make m bouquets.

Example

Input
bloomDay = [1,10,3,10,2], m = 3, k = 1
Output
3
Explanation
Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.

Python solution

Python
class Solution:
    def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
        def check(days: int) -> int:
            cnt = cur = 0
            for x in bloomDay:
                cur = cur + 1 if x <= days else 0
                if cur == k:
                    cnt += 1
                    cur = 0
            return cnt >= m

        mx = max(bloomDay)
        l = bisect_left(range(mx + 2), True, key=check)
        return -1 if l > mx else l

Complexity

MeasureComplexity
TimeO(n \times \log M), where n and M are the number of flowers in the garden and the maximum blooming day, respectively
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1482. Minimum Number of Days to Make m Bouquets is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1482. Minimum Number of Days to Make m Bouquets?
LeetCode 1482. Minimum Number of Days to Make m Bouquets is rated Medium on LeetCode.
What is the time complexity of LeetCode 1482. Minimum Number of Days to Make m Bouquets?
The Python solution on this page runs in O(n \times \log M), where n and M are the number of flowers in the garden and the maximum blooming day, respectively.
What is the space complexity of LeetCode 1482. Minimum Number of Days to Make m Bouquets?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1482. Minimum Number of Days to Make m Bouquets cover?
LeetCode 1482. Minimum Number of Days to Make m Bouquets is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview