A flowerbed is a row of plots, given as an array flowerbed of 0s and 1s: 0 is an empty plot and 1 already holds a flower. Two flowers may never sit in plots that are next to each other, and the bed you are given already follows that rule.
Return true if you can plant n more flowers in empty plots without breaking the rule, and false if you cannot.
Example 1
Input: flowerbed = [0, 0, 1, 0, 0, 0, 0, 1, 0], n = 2 Output: true Why: plant at index 0 and index 4
2 more examples and the constraints
Example 2
Input: flowerbed = [1, 0, 0, 0, 0, 1, 0, 0], n = 3 Output: false Why: only two flowers fit, for example at 2 and 7
Example 3
Input: flowerbed = [0], n = 1 Output: true Why: a single empty plot has no neighbours
Constraints
- 1 ≤ length of flowerbed ≤ 20,000
- Every plot is 0 or 1, and no two 1s are next to each other
- 0 ≤ n ≤ length of flowerbed
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count the runs of empty plotsO(m)
- Plant greedily, left to rightO(m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 plots | Verdict |
|---|---|---|---|
| Count the runs of empty plots | O(m) | Passes; mind the edges | |
| Plant greedily, left to right | O(m) | Best; stops once n are planted |
m = number of plots. Both read each plot at most once; the greedy loop can stop early.
Edge cases to test
- n is 0. Nothing needs planting, so the answer is true even for a full bed.
- One plot. [0] fits one flower; [1] fits none.
- Edges. In [0, 0, 1], index 0 has no left neighbour, so it can take a flower.
- All empty. Five empty plots fit three flowers, at 0, 2 and 4.
Common mistakes
- Treating the first and last plots as blocked because they lack a neighbour.
- Counting a free plot without marking it, so the plot right after it also looks free.
- Checking
n == 0only at the end and missing the case n = 0, or reading past the array at the last index.
How to talk through it
- 1Clarify. Can n be 0? Is the bed I get always valid, with no two flowers already touching?
- 2State the rule. A plot is free when it and both neighbours are empty; a missing neighbour counts as empty.
- 3Argue the greedy. Planting at the first free plot only blocks the plot to its right, so it never does worse than waiting.
- 4Code it. Mark each new flower in the array and stop as soon as n reaches 0.
- 5Test out loud. Run n = 0, a single plot and a bed whose free plots are at the edges.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?