Pattern: Greedy → plant as early as possible
Difficulty: Easy
Time: O(n) | Space: O(1) extra
Problem
A flowerbed is an array of 0 (empty) and 1 (planted). Flowers can’t be planted next to each other.
Can you plant n more flowers without breaking that rule?
flowerbed = [1,0,0,0,1], n = 1 → true (plant in the middle)
flowerbed = [1,0,0,0,1], n = 2 → false
Core idea
Walk left to right. If a spot and both its neighbours are empty, plant there right away.
- Skip spots that are already planted.
- A spot is plantable when left is empty and right is empty.
- Off the edge counts as empty (index
-1and indexlength).
- Off the edge counts as empty (index
- Plant it (
flowerbed[i] = 1), decreasen, and skip the next spot. - Stop early once
nhits 0.
Why greedy works: planting at the earliest possible spot never blocks more spots than planting later would. Waiting can’t help.
Code (TypeScript)
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
for (let i = 0; i < flowerbed.length && n > 0; i++) {
if (flowerbed[i] === 1) continue;
const leftEmpty = i === 0 || flowerbed[i - 1] === 0;
const rightEmpty = i === flowerbed.length - 1 || flowerbed[i + 1] === 0;
if (leftEmpty && rightEmpty) {
flowerbed[i] = 1; // plant it so the next check sees it
n--;
i++; // the next spot is now blocked, skip it
}
}
return n === 0;
}Gotchas
- Edges: the first and last spots only have one neighbour. Treat “off the edge” as empty.
- Mark the plant. If you don’t set
flowerbed[i] = 1,[0,0,0]would plant at 0 and 1. n = 0is alwaystrue, even for[1].- This changes the input array. If that’s not allowed, track “planted previous spot” in a variable instead.
- Test:
[0]withn=1,[0,0,1,0,0]withn=2,[1,0,0,0,0,1]withn=2(false).
Pattern to remember
“Take it as soon as it’s allowed” is greedy. It works when taking now never makes later choices worse.
Related
- Kids With the Greatest Number of Candies (LC 1431)
- Reverse Vowels of a String (LC 345) is next in LeetCode 75