Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

The first day enough adjacent flowers are open

Medium · Target 20 minutes · Binary search · Type asked atGoogleMeta

Flowers stand in a row; flower i opens on day bloom[i] and stays open. A bouquet takes k adjacent open flowers, and each flower can be used in one bouquet only. Return the earliest day on which m bouquets can be made, or −1 if that never happens.

Examples

InputOutputWhy
bloom = [1, 10, 3, 10, 2], m = 3, k = 13By day 3, flowers 0, 2 and 4 are open.
bloom = [1, 10, 3, 10, 2], m = 3, k = 2-1Six flowers are needed and there are five.
bloom = [7, 7, 7, 7, 12, 7, 7], m = 2, k = 312On day 7 only one run of three exists; day 12 joins the gap.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ bloom[i] ≤ 10⁹
  • 1 ≤ m ≤ 10⁶, 1 ≤ k ≤ n

Hints

Hint 1

If m × k is more than the number of flowers, the answer is −1 whatever the days are.

Hint 2

For a fixed day d, how many bouquets can you make? Scan left to right, counting consecutive open flowers, and cut a bouquet each time the count reaches k.

Hint 3

A later day opens more flowers and never closes one, so the count never falls. Search the first day with count ≥ m.

Where people lose marks

  • Computing m × k in 32 bits: 10⁶ × 10⁵ overflows.
  • Counting all open flowers rather than runs of adjacent ones.
  • Not resetting the run to zero after cutting a bouquet, which lets one flower serve two bouquets.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.