Can Place Flowers - Leetcode 605 - Python

preview_player
Показать описание
Don't forget to check the following links:

Notes and theory:

Refined solution:

My blog:

The algorithm begins by creating a new list `padded`, which consists of the original `flowerbed` prefixed and suffixed with a single `0`. This ensures that edge positions in the bed can be evaluated uniformly without special casing. We also initialize an integer counter `total` to track how many new flowers have been planted. Two Boolean variables, `prev` and `curr`, represent whether the previous and current positions (in the `padded` array) are empty (i.e., equal to 0). Initially, `prev` is set based on `padded[0]` and `curr` on `padded[1]`, preparing for a sliding window over the remaining elements.

Next, we iterate through each element `f` in `padded[2:]`, treating `f` as the “next” position in the sliding window. At each step, we check if `prev`, `curr`, and `f == 0` are all true—if so, we plant a flower at `curr` by incrementing `total`, setting `prev = False` (marking the newly planted slot as occupied), and leaving `curr = True` (since `f` remains empty for the next iteration). If the three-slot window is not all empty, we simply slide forward by assigning `prev = curr` and `curr = (f == 0)`. After planting, or after shifting, we immediately check if `total greater than n`; if it is, we return `True` early to indicate that the required number of flowers can be planted.

Once the loop finishes without an early exit, we compare `total` to `n` one last time and return the result. Because we pad the list in O(m) time and make a single pass over its m+2 elements, the time complexity is O(m). The extra space used is O(m) for the `padded` array, plus only O(1) for counters and Boolean flags, making the space complexity O(m).
Рекомендации по теме
visit shbcf.ru