Can Place Flowers

easy array greedy

Problem

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

Inputbed = [1, 0, 0, 0, 1], n = 1
Outputtrue
Plant in position 2: result becomes [1, 0, 1, 0, 1].

def can_place_flowers(bed, n):
    i = 0
    while i < len(bed) and n > 0:
        if bed[i] == 0 \
                and (i == 0 or bed[i - 1] == 0) \
                and (i == len(bed) - 1 or bed[i + 1] == 0):
            bed[i] = 1; n -= 1
        i += 1
    return n == 0
function canPlaceFlowers(bed, n) {
  for (let i = 0; i < bed.length && n > 0; i++) {
    if (bed[i] === 0
        && (i === 0 || bed[i - 1] === 0)
        && (i === bed.length - 1 || bed[i + 1] === 0)) {
      bed[i] = 1; n--;
    }
  }
  return n === 0;
}
class Solution {
    public boolean canPlaceFlowers(int[] bed, int n) {
        for (int i = 0; i < bed.length && n > 0; i++) {
            if (bed[i] == 0
                    && (i == 0 || bed[i - 1] == 0)
                    && (i == bed.length - 1 || bed[i + 1] == 0)) {
                bed[i] = 1; n--;
            }
        }
        return n == 0;
    }
}
bool canPlaceFlowers(vector<int>& bed, int n) {
    for (int i = 0; i < (int)bed.size() && n > 0; i++) {
        if (bed[i] == 0
                && (i == 0 || bed[i - 1] == 0)
                && (i == (int)bed.size() - 1 || bed[i + 1] == 0)) {
            bed[i] = 1; n--;
        }
    }
    return n == 0;
}
Time: O(L) Space: O(1)