Python 0605.py
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if n == 0:
return True
flowerbed = [0] + flowerbed + [0]
spots = 0
for i in range(2, len(flowerbed)):
if flowerbed[i - 2] == 0 and flowerbed[i - 1] == 0 and flowerbed[i] == 0:
spots += 1
if spots == n:
return True
flowerbed[i - 1] = 1
return False
Difficulty
and has an acceptance rate of about 29% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Greedy
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether a given number of new flowers can be planted in a linear flowerbed without violating the rule that no two adjacent plots may both contain flowers. The algorithm first handles the trivial case where no new flowers are required, then pads the original flowerbed with sentinel zeros to simplify boundary checks. It iterates through the padded array, looking for three consecutive empty plots, places a flower in the middle plot when possible, and stops early as soon as the required number of flowers have been placed.
Key Steps
Handling the zero-flower request
if n == 0:
return True
When the caller asks to place zero flowers, the function immediately returns True because the requirement is already satisfied regardless of the current state of the flowerbed.
Adding sentinel zeros
flowerbed = [0] + flowerbed + [0]
By inserting a zero at both the beginning and the end of the list, the algorithm eliminates the need for separate boundary conditions when checking the first and last plots. This transformation guarantees that every original plot has a left and a right neighbor in the padded array.
Scanning for viable planting spots
spots = 0
for i in range(2, len(flowerbed)):
if flowerbed[i - 2] == 0 and flowerbed[i - 1] == 0 and flowerbed[i] == 0:
spots += 1
if spots == n:
return True
flowerbed[i - 1] = 1
The loop starts at index 2, which corresponds to the first original plot after padding. For each position i, the algorithm checks the triple consisting of the plot two steps back, one step back, and the current plot. If all three are empty, the middle plot (i-1) is a valid location for a new flower. The counter spots is incremented, and the middle plot is marked as occupied to prevent subsequent placements from overlapping. An early exit occurs as soon as the number of placed flowers reaches the requested amount n.
Final result when insufficient spots are found
return False
If the loop completes without reaching the target count, the function returns False, indicating that the flowerbed cannot accommodate the requested number of new flowers under the adjacency constraint.
Edge Cases Handled
The algorithm gracefully manages several edge conditions without additional branching logic. When the original flowerbed is empty, the sentinel padding creates a three-element list [0, 0, 0], allowing the loop to detect a single viable spot if n is one. If the flowerbed consists entirely of occupied plots, the triple-zero check never succeeds, and the function correctly returns False unless n is zero, which is handled at the start. The sentinel zeros also cover scenarios where the first or last plot is empty, ensuring that planting at the very ends is considered without risking an out-of-range access.
Performance Optimizations
The most notable optimization is the early termination condition inside the scanning loop. By returning True immediately after the required number of flowers have been placed, the algorithm avoids unnecessary traversal of the remainder of the flowerbed. Additionally, the in-place update flowerbed[i - 1] = 1 eliminates the need for a separate data structure to track newly planted flowers, keeping memory usage minimal. The use of a single pass over the padded array ensures that the work performed scales linearly with the length of the input, and the sentinel padding eliminates extra conditional checks that would otherwise be required at the boundaries.
ELI5 - Simplified Explanation
Imagine a long garden path with little spots where flowers can grow. A zero means a spot is empty, and a one means a flower is already blooming there. To keep the flowers happy, no two flowers are allowed to be right next to each other.
The code starts by adding an extra empty spot at the very beginning and the very end of the path to make sure the flowers on the edges have enough room. It then walks along the path, checking three spots at a time. It looks for a sequence of three empty spots in a row. When it finds three empty spots together, it decides to plant a flower in the middle one.
Every time a new flower is planted, the count of flowers goes up by one. After planting the flower, the code marks that spot as full. It keeps walking down the path repeating this process until all the flowers are planted or it runs out of space. If it manages to plant all the flowers requested, the path is ready. If it finishes walking and still has more flowers to plant, then that path was not big enough for them all.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | PHP | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 495: Teemo Attacking
- problem 735: Asteroid Collision
Solved On The Same Day
- problem 257: Binary Tree Paths
- problem 551: Student Attendance Record I
- problem 236: Lowest Common Ancestor of a Binary Tree
- problem 289: Game of Life
- problem 397: Integer Replacement
- problem 413: Arithmetic Slices
- problem 525: Contiguous Array
- problem 567: Permutation in String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality