Date and Time: Sep 14, 2024, 21:44 (EST)
Link: https://leetcode.com/problems/can-place-flowers/
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
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 true
if n
new flowers can be planted in the flowerbed
without violating the no-adjacent-flowers rule and false
otherwise.
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
-
1 <= flowerbed.length <= 2 * 10^4
-
flowerbed[i]
is0
or1
. -
There are no two adjacent flowers in
flowerbed
. -
0 <= n <= flowerbed.length
We can just append two extra [0]
before and after flowerbed
, so we can check flowerbed[i-1], flowerbed[i], flowerbed[i+1]
, if they are all 0
, which means we can plant a flower and decrement n
. Finally, we return n <= 0
, so we know whether we can plant n
flowers or not.
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
# For each i in flowerbed, check itself and if its neighbors are 0, if so, replace 0 to be 1 and decrement n
# Finally, check if n <= 0 to know if we can place flowers
# 0 [1,0,0,0,1] 0
# TC: O(n), n=len(flowerbed), SC: O(1)
flowerbed = [0] + flowerbed + [0]
for i in range(1, len(flowerbed)-1):
if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
n -= 1
flowerbed[i] = 1
return n <= 0
Time Complexity: n
is the length of flowerbed
.
Space Complexity: