Solution: Can Place Flowers

Let’s solve the Can Place Flowers problem using the Greedy Techniques pattern.

Statement

Given an integer list flowerbed, each element is either 00 (indicating an empty plot) or 11 (indicating a planted plot), and an integer 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:

  • 11\leq flowerbed.length 103\leq10^3

  • 00\leq n \leq flowerbed.length

  • flowerbed[i] is 00 or 11.

  • 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:

  1. Set a counter to 00, which tracks the number of flowers successfully planted.

  2. For each position in the flowerbed:

    1. Check if the current index is 00 (indicating an empty plot):

      1. Check if the current index’s left and right neighbors of the current index are also 00 or if the current index is at the boundary of the flowerbed.

      2. Left condition: The current index is the first plot (left boundary), or the current index  1-~1 is 00.

      3. Right condition: The current index is the last plot (right boundary), or the current index + 1+~1 is 00.

      4. If both left and right conditions are satisfied:

        1. Place a flower at the current index position and increment the count by 11.

      5. After planting, if the count equals nn, return TRUE as the required number of flowers is planted.

    2. Otherwise, move on to the next index if the current index is 11 (indicating a flower).

  3. If the loop finishes without planting nn 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.