Code Logo

Can Place Flowers

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
[1,0,0,0,1], 2
Output
false
Explanation

Only one spot available.

Example 2
Input
[1,0,1], 0
Output
true
Explanation

Zero flowers always works.

Example 3
Input
[0,0,0], 2
Output
true
Explanation

Available: indices 0 and 2.

Example 4
Input
[], 0
Output
true
Explanation

Empty, no flowers to plant.

Example 5
Input
[1,0,0,0,1], 1
Output
true
Explanation

Plant at index 2.

Algorithm Flow

Recommendation Algorithm Flow for Can Place Flowers
Recommendation Algorithm Flow for Can Place Flowers

Solution Approach

Iterate through plots. If empty and neighbors are empty/absent, plant and decrement n.

function solution(flowerbed, n) {
  for (var i = 0; i < flowerbed.length && n > 0; i++) {
    if (flowerbed[i] === 0) {
      var prev = i === 0 ? 0 : flowerbed[i-1];
      var next = i === flowerbed.length-1 ? 0 : flowerbed[i+1];
      if (prev === 0 && next === 0) {
        flowerbed[i] = 1;
        n--;
      }
    }
  }
  return n <= 0;
}

Time O(n), Space O(1).

Best Answers

java
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;
    }
}