We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy greedy problem, graded against 6 test cases (3 of them hidden).
Take the locally best option each step and prove it stays globally optimal.
Reach for it when you see: Interval scheduling, jump/reachability questions, or an optimisation with an obvious local choice.
More Greedyproblems →Scanning left to right and planting at the first legal opportunity is optimal. The intuition: skipping a legal plot can never help, because planting there only ever blocks the immediately adjacent plot - which was unusable anyway once you planted anywhere in that gap. Formally, an exchange argument shifts any solution's leftmost flower left to the greedy choice without reducing the count.
A plot qualifies when it is empty and both neighbours are empty, with out-of-bounds treated as empty. That boundary convention is where most wrong answers live: `[0]` allows one flower, and `[0,0]` also allows exactly one, but code that reads `flowerbed[-1]` or runs past the end mishandles both.
Two implementation notes. Mutating the array as you plant is what keeps the adjacency check correct for the next position - without it, `[0,0,0]` would count two flowers. And you can return `true` as soon as the count reaches `n`, which avoids scanning the rest and, more importantly, avoids overflow concerns if the count were allowed to grow unbounded.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.