LeetCode: Can Place Flowers

Determine if a certain number of flowers can be planted in a flowerbed without violating the no-adjacent-flowers rule.

Posted on LeetCode Python

Solution

Hint: think about how you can skip over the greatest number of spots.

If there is a flower in the next spot, you can skip three spots ahead.

Skip next 3 spots

If there is a flower in the current spot, you can skip two spots ahead.

Skip next 2 spots

Notice that we never need to check the previous spot.

Runtime

3 ms | Beats 95.70%

class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
i = 0
while n > 0 and i < len(flowerbed):
if i < len(flowerbed) - 1 and flowerbed[i + 1] == 1:
i += 3
elif flowerbed[i] == 1:
i += 2
else:
flowerbed[i] = 1
n -= 1
i += 2
return n == 0