AAlgoLoopSpaced repetition for LeetCode
EASYGreedyLeetCode ↗

Can Place Flowers

The key idea

Scan left to right and greedily plant a flower in any empty slot whose left and right neighbors are also empty. Treating the out-of-bounds ends as empty lets the boundary slots be handled by the same rule. Planting as early as possible is always safe and never blocks a better future placement.

Problem

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

Constraints

Examples

Input: flowerbed=[1,0,0,0,1], n=1 Output: true
Input: flowerbed=[1,0,0,0,1], n=2 Output: false

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Greedy problems