Can Place Flowers — LeetCode 605 Python Solution
EasyGreedyArray
- Problem
- #605
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- flowerbed = [1,0,0,0,1], n = 1
- Output
- true
Python solution
Python
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
flowerbed = [0] + flowerbed + [0]
for i in range(1, len(flowerbed) - 1):
if sum(flowerbed[i - 1 : i + 2]) == 0:
flowerbed[i] = 1
n -= 1
return n <= 0Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array flowerbed |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 605. Can Place Flowers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 605. Can Place Flowers?
- LeetCode 605. Can Place Flowers is rated Easy on LeetCode.
- What is the time complexity of LeetCode 605. Can Place Flowers?
- The Python solution on this page runs in O(n), where n is the length of the array flowerbed.
- What is the space complexity of LeetCode 605. Can Place Flowers?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 605. Can Place Flowers cover?
- LeetCode 605. Can Place Flowers is tagged Greedy and Array on LeetCode.