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.
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.
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.
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.
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.
Index 0 treats its missing left neighbor as empty. The last index treats its missing right neighbor as empty. Boundaries are free real estate.
A single pass through the flowerbed decides every plot's fate.
Clone the flowerbed so mutations don't affect the caller. Set plantedFlowers = 0.
For each index, compute three booleans: leftEmpty, currentEmpty, rightEmpty. Boundary indices treat the missing neighbor as empty.
Set workingBed[index] = 1 and increment the counter. This mutation ensures the next index sees its left neighbor as occupied.
If plantedFlowers ≥ n after any plant, return true immediately. After the loop, return plantedFlowers ≥ n.
Boundary conditions and density limits test the algorithm's correctness.
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.
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.
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.