Scan from left to right and plant whenever the current and neighboring plots are empty. Each earliest valid placement leaves maximum room for later flowers.
Complexity
O(n) time and O(1) extra space.
Determine whether enough flowers can be planted without placing any two in adjacent plots.
Scan from left to right and plant whenever the current and neighboring plots are empty. Each earliest valid placement leaves maximum room for later flowers.
O(n) time and O(1) extra space.
package main
func canPlaceFlowers(flowerbed []int, n int) bool {
for index := 0; index < len(flowerbed) && n > 0; index++ {
leftEmpty := index == 0 || flowerbed[index-1] == 0
rightEmpty := index == len(flowerbed)-1 || flowerbed[index+1] == 0
if flowerbed[index] == 0 && leftEmpty && rightEmpty {
flowerbed[index] = 1
n--
}
}
return n == 0
}
class Solution:
def canPlaceFlowers(self, flowerbed: list[int], n: int) -> bool:
if n == 0:
return True
for index, plot in enumerate(flowerbed):
left_empty = index == 0 or flowerbed[index - 1] == 0
right_empty = index == len(flowerbed) - 1 or flowerbed[index + 1] == 0
if plot == 0 and left_empty and right_empty:
flowerbed[index] = 1
n -= 1
if n == 0:
return True
return False
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
for (let index = 0; index < flowerbed.length && n > 0; index += 1) {
const leftEmpty = index === 0 || flowerbed[index - 1] === 0;
const rightEmpty = index === flowerbed.length - 1 || flowerbed[index + 1] === 0;
if (flowerbed[index] === 0 && leftEmpty && rightEmpty) { flowerbed[index] = 1; n -= 1; }
}
return n === 0;
}