Solution: Can Place Flowers
Let’s solve the Can Place Flowers problem using the Greedy Techniques pattern.
We'll cover the following
Statement
Given an integer list flowerbed
, each element is either n
. Determine if n
new flowers can be planted without violating the rule that no two flowers can be planted in adjacent plots. Return TRUE if it’s possible to plant all n
flowers. Otherwise, return FALSE.
Constraints:
flowerbed.length
n
flowerbed.length
flowerbed[i]
isor . There are no two adjacent flowers in the
flowerbed
.
Solution
This solution applies a greedy approach to determine if the required number of flowers can be planted in the flowerbed without placing two flowers next to each other. Through the greedy technique, flowers are planted in the flowerbed at the earliest possible empty positions when a spot is not adjacent to any flower. By filling these valid plots, the flower count is increased avoiding future conflicts with potential plantable spots further in the list. This way, chances of planting the flowers without needing to look ahead or reconsider earlier decisions are maximized.
Here’s the step-by-step implementation of the solution:
Set a counter to
, which tracks the number of flowers successfully planted. For each position in the
flowerbed
:Check if the current index is
(indicating an empty plot): Check if the current index’s left and right neighbors of the current index are also
or if the current index is at the boundary of the flowerbed
.Left condition: The current index is the first plot (left boundary), or the current index
is . Right condition: The current index is the last plot (right boundary), or the current index
is . If both left and right conditions are satisfied:
Place a flower at the current index position and increment the count by
.
After planting, if the count equals
, return TRUE as the required number of flowers is planted.
Otherwise, move on to the next index if the current index is
(indicating a flower).
If the loop finishes without planting
flowers, return FALSE; otherwise, return TRUE.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.