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.
You are 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: trueExample 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: falseConstraints:
1 <= flowerbed.length <= 20,000flowerbed[i] is 0 or 1.0 <= n <= flowerbed.lengthBefore attempting this problem, you should be comfortable with:
A flower can be planted at position i only if positions i-1, i, and i+1 are all empty. To handle edge cases at the boundaries, we pad the flowerbed with zeros at both ends. This way, we can apply the same rule uniformly across all positions without special boundary checks.
0 prepended and appended to the original flowerbed.1 to length-2 (the original positions).1, and decrement n.true if n is 0 or less (we placed enough flowers).Instead of checking each position individually, we can count consecutive empty plots between flowers. For a sequence of k empty plots between two flowers, we can plant (k-1)/2 flowers. At the beginning and end of the flowerbed, the formula differs slightly since there is no blocking flower on one side: we can plant k/2 flowers at the edges.
1 (treating the left boundary as open).1), calculate how many new flowers can fit in the empty sequence before it using (empty-1)/2, then reset the counter.0), increment the counter.empty/2 (right boundary is open).true if we placed at least n flowers.After deciding to plant a flower at position i, you must update the flowerbed to reflect the new flower. Otherwise, you may count overlapping positions as valid.
# Wrong: not updating the flowerbed after planting
if f[i-1] == 0 and f[i] == 0 and f[i+1] == 0:
n -= 1 # Missing: f[i] = 1When not padding the array, forgetting to handle the first and last positions specially leads to index-out-of-bounds errors or incorrect neighbor checks.