605. Can Place Flowers
Asked at 14Meta50Microsoft41Google40Amazon39Apple22Bloomberg22LinkedIn78Infosys30SOTI100Nutanix60Atlassian48Airbnb38Yandex36Oracle27
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
assert Solution().canPlaceFlowers([1, 0, 0, 0, 1], 1) is True
assert Solution().canPlaceFlowers([1, 0, 0, 0, 1], 2) is False
assert Solution().canPlaceFlowers([0], 1) is True
assert Solution().canPlaceFlowers([0, 0, 1, 0, 0], 2) is True
assert Solution().canPlaceFlowers([1, 0, 1, 0, 1], 0) is True
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int len = flowerbed.length;
for (int i = 0; i < len && n > 0; i++) {
boolean leftFree = i == 0 || flowerbed[i - 1] == 0, rightFree = i == len - 1 || flowerbed[i + 1] == 0;
if (flowerbed[i] == 0 && leftFree && rightFree) { flowerbed[i] = 1; n--; }
}
return n <= 0;
}
}
func canPlaceFlowers(flowerbed []int, n int) bool {
bed := append(append([]int{0}, flowerbed...), 0) // pad both ends with empty plots
for i := 1; i < len(bed)-1; i++ {
if bed[i-1] == 0 && bed[i] == 0 && bed[i+1] == 0 { // planting as early as possible is optimal
bed[i] = 1
n--
}
}
return n <= 0
}