SDE & MLE Prep

605. Can Place Flowers

Problem

flowerbed holds 0 (empty) and 1 (planted), and no two flowers may be adjacent. Decide whether n new flowers can be planted without breaking the rule.

Example: flowerbed = [1,0,0,0,1]: n = 1 → true; n = 2 → false

Planting as early as possible never hurts (an earlier flower blocks at most what a later one would). Pad both ends with 0 and plant wherever a spot and both neighbours are empty.

Complexity: O(n).

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