Leetcode 605. Can Place Flowers
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.
flowerbed = [1,0,0,0,1]
, n = 1
true
flowerbed = [1,0,0,0,1]
, n = 2
false
To solve this problem, we’ll iterate through the flowerbed
array and look for potential spots where a new flower can be planted while adhering to the no-adjacent-flowers rule. We’ll follow these steps:
n
, return true.n
, return false.#include <vector>
bool canPlaceFlowers(std::vector<int>& flowerbed, int n) {
int count = 0;
int len = flowerbed.size();
for (int i = 0; i < len; ++i) {
if (flowerbed[i] == 0) {
// Check if the previous and next positions are 0 or out of bounds
bool emptyPrev = (i == 0 || flowerbed[i-1] == 0);
bool emptyNext = (i == len - 1 || flowerbed[i+1] == 0);
if (emptyPrev && emptyNext) {
// Plant the flower here
flowerbed[i] = 1;
count++;
// Check if we have planted enough flowers
if (count >= n) {
return true;
}
}
}
}
return count >= n;
}
The time complexity of the solution is (O(N)), where (N) is the length of the flowerbed array. This is because we are making a single pass through the array to check possible planting spots and update the flowerbed.
flowerbed[i] == 0
), we check if the previous (i-1
) and next (i+1
) plots are also empty or out of bounds.flowerbed[i] = 1
and increase the count of planted flowers.n
, we return true quickly. If the loop ends and the count is still less than n
, we return false, as it’s not possible to plant the required number of flowers.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?