Minimum Number of Days to Make m Bouquets (LeetCode 1482)
This problem is a classic example of the Binary Search on Answer pattern. Instead of searching within an array, we search for the minimum day on which it becomes possible to make the required bouquets.
Initially, the problem may look confusing because it combines conditions like adjacency, grouping, and minimum constraints. But once the problem is reframed correctly, the solution becomes systematic.
🔍 Problem Understanding
You are given an array bloomDay where each value represents the day a flower blooms.
To make m bouquets:
- Each bouquet needs exactly
kadjacent flowers - A flower can be used only once
- You must minimize the number of days
If it is impossible to make m bouquets, return -1.
💡 Key Insight
Instead of asking "How many bouquets can I make?", the real question is:
By dayX, is it possible to make at leastmbouquets?
This question has a monotonic property:
- If it is possible on day
X, it will also be possible on any later day - If it is not possible on day
X, it won’t be possible on earlier days
This monotonic behavior makes the problem ideal for binary search.
🧠 Approach
- Binary search on the range
[min(bloomDay), max(bloomDay)] - For each mid day, check feasibility using a helper function
- The helper function counts adjacent bloomed flowers
- Once
kadjacent flowers are found, one bouquet is formed - Return
trueif at leastmbouquets can be made
✅ Python Solution
class Solution:
def possible(self, bloomDay, m, k, mid):
count = 0
adj = 0
for day in bloomDay:
if day <= mid:
adj += 1
else:
adj = 0
if adj == k:
count += 1
adj = 0
return count >= m
def minDays(self, bloomDay, m, k):
if len(bloomDay) < m * k:
return -1
s = min(bloomDay)
e = max(bloomDay)
while s < e:
mid = (s + e) // 2
if self.possible(bloomDay, m, k, mid):
e = mid
else:
s = mid + 1
return s
🔗 GitHub Solution: View on GitHub
📈 Time Complexity Analysis
| Component | Complexity |
|---|---|
| Binary Search Range | O(log(maxDay - minDay)) |
| Feasibility Check | O(n) |
| Total Time Complexity | O(n log D) |
| Space Complexity | O(1) |
📊 Time Complexity Growth (Conceptual)
As the size of bloomDay increases, each feasibility check scans the entire array,
while binary search reduces the number of days tested logarithmically.
Days Range (D) ───────────────▶ Binary Search ───────▶ log D Array Scan ───────────────▶ n Total ───────────────▶ n log D
🏁 Final Takeaway
This problem becomes straightforward once you identify it as a Binary Search on Answer problem. The key is designing a clean feasibility function that answers a simple yes/no question.
Returning a boolean instead of counts makes the solution more intuitive, readable, and interview-friendly.
Comments
Post a Comment
Share your views on this blog😍😍