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
- 1 <= flowerbed.length <= 2 * 10^4
- flowerbed[i] is 0 or 1
- There are no two adjacent flowers in flowerbed.
- 0 <= n <= flowerbed.length
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
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Greedy problems
- Assign CookiesEASY
- Best Time to Buy and Sell Stock IIMEDIUM
- Boats to Save PeopleMEDIUM
- CandyHARD
- Dota2 SenateMEDIUM
- Gas StationMEDIUM
- Hand of StraightsMEDIUM
- Increasing Triplet SubsequenceMEDIUM
- Jump GameMEDIUM
- Jump Game IIMEDIUM
- Lemonade ChangeEASY
- Longest Happy StringMEDIUM