Can Place Flowers

by raviteja gunda

HTML

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 true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

JavaScript

function canPlaceFlowers(flowerbed: number[], n: number): boolean {
    if(n === 0) {
        return true;
    }       
    for(let i: number = 0; i < flowerbed.length && n > 0; i++) {
        if(!flowerbed[i] && !flowerbed[i+1] && !flowerbed[i-1]) {
                flowerbed[i] = 1;
                n--;
            }
    }
    return n <= 0;
};


//top

function canPlaceFlowers(flowerbed: number[], n: number): boolean {

    if (n === 0) {
        return true;
    }

    let count = 0;
    for (let i: number = 0; i < flowerbed.length; i++) {

        const current = flowerbed[i];
        const prev = flowerbed[i-1];
        const next = flowerbed[i+1];

        // Adjacent = ensure all elements behind, currently and ahead are zero
        if (!current && !prev && !next) {
            count++;
            flowerbed[i] = 1;
        }
    }

    return count >= n;
};