Can Place Flowers

Easy GreedyArray

Problem

Flowers cannot be planted in adjacent plots. Given a flowerbed (0 = empty, 1 = planted) and n, return true iff n new flowers can be planted.

Example 1 Input: [1,0,0,0,1], n=1 Output: true
Example 2 Input: [1,0,0,0,1], n=2 Output: false

Constraints

Approach — Greedy

This is a Greedy problem. The idea: make the locally best choice at each step, which provably builds up to the global optimum here. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n log n) time.

Solution code

Python

class Solution:
    def canPlaceFlowers(self, flowerbed, n):
        bed = [0] + flowerbed + [0]
        for i in range(1, len(bed) - 1):
            if bed[i - 1] == 0 and bed[i] == 0 and bed[i + 1] == 0:
                bed[i] = 1
                n -= 1
        return n <= 0

Java

class Solution {
    public boolean canPlaceFlowers(int[] f, int n) {
        for (int i = 0; i < f.length && n > 0; i++) {
            if (f[i] == 0 && (i == 0 || f[i-1] == 0) && (i == f.length - 1 || f[i+1] == 0)) {
                f[i] = 1; n--;
            }
        }
        return n <= 0;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Can Place Flowers interactively → ← All solutions