Problem
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.
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 if n
new flowers can be planted in the flowerbed
without violating the no-adjacent-flowers rule.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Greedy approach - Add 2 spots to flowerbed
Lets see examples
[1, 0, 1]
-> We cannot place flower, as sides already are bounded by flower
[1, 0, 0, 1]
-> We cannot place flower
[1, 0, 0, 0, 1]
-> We can now place the flowers
So, we need atleast 3 empty space to put 1 flower, 5 to place 2 and so on;
But there is a problem, what if array doesn’t start with 0 OR end with 0? For eg.
[0, 0, 1]
-> Now we can place the flower at index 0.
So, its good to assume 2 empty spots before 0th and last index of array.
So, we can append these to the array and proceed.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
Method 2 - Using Greedy approach without using aux array
We can also do it without creating extra array, we can also just take care of the side conditions.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
Method 3 - Greedy by counting continuous flowerbed points
We can just count number of flowerbed points that are empty continuously.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)