Can Place Flowers · Optimal Solution

Plant greedily. Never look back.

A gardener walks a row of flower plots from left to right. Each empty plot with no immediate neighbors gets a flower — no planning, no backtracking. This greedy strategy works because planting at the earliest available spot never blocks a placement that a later strategy could have used. One scan checks three neighbors per plot: left, current, right. If all are empty, plant and move on. O(n) time. O(1) extra space.


Interactive

Watch the gardener walk the flowerbed


Concept

Three checks, one decision

At every plot the algorithm asks exactly one compound question: are the left neighbor, the current cell, and the right neighbor all empty? If yes, plant. If no, move on. That's the entire logic.

three-neighbor check

Left, current, and right must all be zero. If any one is occupied, planting here would violate the no-adjacent-flowers rule. The check is a simple triple-AND.

greedy invariant

Planting at the leftmost available spot never reduces total capacity. Skipping it to plant later can only waste a slot — the greedy choice is always safe.

boundary as virtual empty

Index 0 treats its missing left neighbor as empty. The last index treats its missing right neighbor as empty. Boundaries are free real estate.


Algorithm

Scan, check, plant, advance

A single pass through the flowerbed decides every plot's fate.

  1. 1

    Copy the bed & initialize counter

    Clone the flowerbed so mutations don't affect the caller. Set plantedFlowers = 0.

  2. 2

    Walk left to right

    For each index, compute three booleans: leftEmpty, currentEmpty, rightEmpty. Boundary indices treat the missing neighbor as empty.

  3. 3

    Plant if all three are empty

    Set workingBed[index] = 1 and increment the counter. This mutation ensures the next index sees its left neighbor as occupied.

  4. 4

    Early exit or final verdict

    If plantedFlowers ≥ n after any plant, return true immediately. After the loop, return plantedFlowers ≥ n.


Edge Cases

Where the gardener gets creative

Boundary conditions and density limits test the algorithm's correctness.

All empty — max density

An empty bed of length k can hold ⌈k/2⌉ flowers. The greedy scanner plants at indices 0, 2, 4, … automatically achieving maximum density without any special logic.

Single plot

A bed of length 1 has both boundaries adjacent. The missing left and missing right are both treated as empty, so the single plot is always plantable — the triple-AND passes trivially.

Insufficient space

When pre-existing flowers fragment the bed into gaps too small or too few, the scanner exhausts every plot without meeting the target. The final comparison planted ≥ n returns false.