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;
};
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.