Can Place Flowers
Problem Statement
You have a flowerbed (array of 0s and 1s, where 0 is empty and 1 is a flower) and want to plant n new flowers. Flowers can’t be planted adjacent to each other. Determine if you can plant all n flowers. This easy-level greedy problem is about spacing—can you fit them all?
Example
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true (plant at index 2)
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false (only one spot available)
Code
Java
Python
JavaScript
public class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int count = 0; int i = 0; while (i < flowerbed.length) { if (flowerbed[i] == 0) { boolean left = (i == 0) || (flowerbed[i-1] == 0); boolean right = (i == flowerbed.length-1) || (flowerbed[i+1] == 0); if (left && right) { flowerbed[i] = 1; count++; i++; } } i++; } return count >= n; } }
def can_place_flowers(flowerbed, n): count = 0 i = 0 while i < len(flowerbed): if flowerbed[i] == 0: left = (i == 0) or (flowerbed[i-1] == 0) right = (i == len(flowerbed)-1) or (flowerbed[i+1] == 0) if left and right: flowerbed[i] = 1 count += 1 i += 1 i += 1 return count >= n
function canPlaceFlowers(flowerbed, n) { let count = 0; let i = 0; while (i < flowerbed.length) { if (flowerbed[i] === 0) { let left = (i === 0) || (flowerbed[i-1] === 0); let right = (i === flowerbed.length-1) || (flowerbed[i+1] === 0); if (left && right) { flowerbed[i] = 1; count++; i++; } } i++; } return count >= n; }
Explanation
- Greedy Choice: Plant flowers whenever possible, checking adjacent plots.
- Flow: Skip planted spots, plant if both sides are empty.
- Example: [1,0,0,0,1] → plant at 2, count=1.
Note
Time complexity: O(n), Space complexity: O(1). Plant wisely!