Home
DSA Patterns
Greedy Algorithms
Can Place Flowers
Can Place Flowers
Decide whether n new flowers fit in a flowerbed where no two flowers may be adjacent, by planting greedily in each empty plot whose neighbours are empty.
Problem Understanding
Can Place Flowers (LeetCode 605): a flowerbed is an array of 0s (empty) and 1s (planted), and flowers cannot be planted in adjacent plots. Given the flowerbed and an integer n, return true if n new flowers can be planted without breaking the rule. The input already follows the rule.
Examples: [1, 0, 0, 0, 1], n = 1 → true; the same bed with n = 2 → false.
The Intuition: Plant at the First Chance
You never gain anything by waiting: an earlier flower leaves at least as much room on the right as a later one.
- Scan left to right.
- Plant in any empty plot whose left and right neighbours are empty, treating the ends as empty.
- Count what you planted and compare with n.
This "take the first choice that keeps you safe" argument is the core of Introduction to Greedy Algorithms.
Interactive Walkthrough
NEED 1 · PLANT AS EARLY AS POSSIBLE
SCAN THE BED
flowerbed (1 = flower)
0
1
2
3
4
Planted
0
Need
1
Answer
:
Scan the bed left to right and plant wherever it fits. Need 1
Next
Plot 0 already has a flower
flowerbed
n
The bed is drawn as LeetCode writes it, 1 for a flower. Flowers already there are outlined; flowers the scan plants turn green. Try Edges to see a plot at the end of the bed take a flower.
Dry Run Table
Input: flowerbed = [1, 0, 0, 0, 1], n = 1.
| Plot | Value | Neighbours empty? | Action | count |
|---|---|---|---|---|
| 0 | 1 | already planted | 0 | |
| 1 | 0 | left is 1 | skip | 0 |
| 2 | 0 | yes | plant | 1 |
| 3 | 0 | left is now 1 | skip | 1 |
| 4 | 1 | already planted | 1 |
1 ≥ 1. Answer: true.
The Solution Template
One pass that plants greedily and counts. Writing the 1 into the bed is what blocks the next plot.
Can Place Flowers Code
1var canPlaceFlowers = function(flowerbed, n) {2 let count = 0;3 for (let i = 0; i < flowerbed.length; i++) {4 if (flowerbed[i] === 0) {5 const left = i === 0 || flowerbed[i - 1] === 0;6 const right = i === flowerbed.length - 1 || flowerbed[i + 1] === 0;7 if (left && right) {8 flowerbed[i] = 1;9 count++;10 }11 }12 }13 return count >= n;14};
Edge Cases & Common Mistakes
- n = 0: always true.
- Single plot
[0]: both neighbours are missing, so it takes one flower. - Not marking the new flower: the next plot would also pass the check, and two adjacent flowers would be counted.
- Counting runs of zeros by formula: possible, but the ends of the bed need separate cases; the scan handles them uniformly.
Summary
Scan once, planting in every empty plot whose neighbours are empty, and check that the count reaches n. Planting early is always safe. O(n) time, O(1) extra space.
More practice: DSA interview questions with answers · patterns cheat sheet
