Problem Description
Given an array representing a flowerbed where 0 means an empty plot and 1 means a plot with a flower, determine if it is possible to plant n new flowers without violating the rule that no two flowers can be adjacent.
Key Insights
- Use a greedy approach by scanning the array once.
- For each position, check if the current plot and its adjacent plots (taking care of edge conditions) are empty.
- If the position is suitable, plant a flower there (simulate by setting it to 1) and skip the next plot.
- Count the number of new flowers planted and compare it with n.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the flowerbed array. Space Complexity: O(1), as the solution uses only a constant amount of extra space.
Solution
The solution iterates through the flowerbed array and checks for available spots to plant a flower. A spot is available if:
- The current plot is empty.
- If it’s not the first plot, the left neighbor is empty.
- If it’s not the last plot, the right neighbor is empty.
Once a valid spot is found:
- Plant a flower by setting the value to 1.
- Increment the count of planted flowers.
- Increment the index by one extra step to skip the adjacent plot (to ensure no adjacent flowers are planted).
If the number of planted flowers meets or exceeds n during the iteration, return true immediately. Otherwise, after the loop, check whether the count is at least n.