Skip to content

Commit

Permalink
Add simpler solution to 0605-can-place-flowers.py
Browse files Browse the repository at this point in the history
Add another O(1) space complexity solution that is simpler and more readable
  • Loading branch information
MHamiid authored Jan 1, 2023
1 parent 0cb22b5 commit b08fe57
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions python/0605-can-place-flowers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
# Solution with O(n) space complexity
f = [0] + flowerbed + [0]

for i in range(1, len(f) - 1): # skip first & last
Expand All @@ -8,6 +9,7 @@ def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
n -= 1
return n <= 0

# Solution with O(1) space complexity
empty = 0 if flowerbed[0] else 1

for f in flowerbed:
Expand All @@ -19,3 +21,17 @@ def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:

n -= (empty) // 2
return n <= 0

# Another solution with O(1) space complexity
for i in range(len(flowerbed)):
if n == 0:
return True
if ((i == 0 or flowerbed[i - 1] == 0) # If at the first element or the previous element equals to 0
and (flowerbed[i] == 0) # If current element equals to 0
and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0)): # If at the last element or the next element equals to 0
# Place flower at the current position
flowerbed[i] = 1
n -= 1

return n == 0

0 comments on commit b08fe57

Please sign in to comment.