Can Place Flowers
You have a flowerbed represented as an array of 0s (empty) and 1s (planted). Flowers cannot be planted in adjacent plots. Given n new flowers, return true if they can all be planted without violating the adjacency rule.
This is a greedy state machine problem that iterates through the flowerbed checking each position i. If the current plot is empty and both neighbors (i-1 and i+1) are empty or out of bounds, plant a flower by setting flowerbed[i] = 1 and decrement n. If n reaches 0, return true early.
The DP aspect is tracking the state change: when we plant a flower, the array is modified for future comparisons. The greedy algorithm scans left to right, making optimal decisions at each step. Planting earlier never reduces future opportunities because planting blocks only adjacent plots, and scanning left to right ensures the left neighbor is already finalized.
Time is O(n) with O(1) extra space. Edge cases include an empty flowerbed (return n == 0), n = 0 (immediately true), and the first and last plots which have only one neighbor to check.
This problem demonstrates how a simple state machine with sequential decision-making can solve optimization problems without backtracking, a core principle of dynamic programming where each decision depends only on the current state.
Example Input & Output
Only one spot available.
Zero flowers always works.
Available: indices 0 and 2.
Empty, no flowers to plant.
Plant at index 2.
Algorithm Flow
Solution Approach
Determine if n flowers can be planted in a flowerbed without violating the no-adjacent rule. Iterate through the bed; if a plot is empty and both neighbors are either empty or out of bounds, plant a flower there and skip the next plot (since it cannot be planted). Count successful plantings and compare with n.
Skipping the next plot after planting (i++) is an optimization since the adjacent plot becomes unavailable. The boundary checks using boolean short-circuit prevent index out of bounds.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public boolean solution(int[] flowerbed, int n) {
for (int i=0;i<flowerbed.length && n>0;i++) {
if (flowerbed[i]==0) {
int p=i==0?0:flowerbed[i-1];
int nx=i==flowerbed.length-1?0:flowerbed[i+1];
if (p==0 && nx==0) { flowerbed[i]=1; n--; }
}
}
return n<=0;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
