Intuition
To check condition in an easier manner, add 0 at the beginning and the end
- Iterate through flowerbed and if i-1 and i and i+1 are all 0, change the current element to 1
- subtract 1 from n
- End the loop if n less than equal to 0
- return n less than equal to 0 at the end to check whether all flowers were planted
Optimal Solution
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n:int) -> bool:
arr = [0] + flowerbed + [0]
for i in range(1,len(arr)-1):
if arr[i-1] == 0 and arr[i] and arr[i+1] == 0:
arr[i] = 1
n -= 1
if n <= 0:
return True
return n <= 0
Time Complexity
Time Complexity O(N)
Space Complexity O(N)