I am working on this leetcode problem 605. Can Place Flowers. I am given a list like flowerbed = [1,0,0,0,1] and an integer like n = 1. The rule is that, 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 if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
This is my code. I'm starting a for loop from index 1 to len(flowerbed)-2 and I am checking if the current value, the value before me and the value after me are all 0 and if so, I'm incrementing counter by 1. At the end, I'm returning a bool by comparing counter with n.
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
counter = 0
for i in range(1, len(flowerbed)-2):
if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
counter += 1
return counter == n
However, for this test case, its telling me that its not checking out. I don't understand why. There are 2 valid spots for a flower on the flower bed.
Input: [1,0,0,0,0,1]
n = 2
Output: true
Expected: false