Can Place Flowers - 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.
Input & Output
Example 1 — Basic Case
$
Input:
flowerbed = [1,0,0,0,1], n = 1
›
Output:
true
💡 Note:
We can plant 1 flower at position 2. Position 1 is invalid (adjacent to flower at 0), position 3 is invalid (adjacent to flower at 4), but position 2 has empty neighbors on both sides.
Example 2 — Not Enough Space
$
Input:
flowerbed = [1,0,0,0,1], n = 2
›
Output:
false
💡 Note:
We can only plant 1 flower at position 2. There's no second valid position that doesn't violate the adjacency rule, so we cannot plant 2 flowers.
Example 3 — Edge Case All Empty
$
Input:
flowerbed = [0,0,0], n = 2
›
Output:
true
💡 Note:
We can plant flowers at positions 0 and 2. Position 1 cannot be used because it would be adjacent to both planted flowers.
Constraints
- 1 ≤ flowerbed.length ≤ 2 × 104
- flowerbed[i] is 0 or 1
- There are no two adjacent flowers in flowerbed
- 0 ≤ n ≤ flowerbed.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Flowerbed array with 0s (empty) and 1s (planted), plus number n
2
Process
Find valid empty positions where both neighbors are empty
3
Output
Return true if we can place n flowers, false otherwise
Key Takeaway
🎯 Key Insight: Use greedy approach - plant whenever you find a valid spot, as early placement never blocks optimal solutions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code