πͺ΄Can Place Flowers - LeetCode 605


π§ Problem Summary
You're given a flowerbed (an array of 0s and 1s), where:
0
β empty plot1
β already planted flower
You need to plant n
new flowers without placing them in adjacent plots. Return true
if it's possible, otherwise false
.
βοΈ Approach
We loop through the flowerbed and greedily place flowers at every valid position:
A flower can be planted at index
i
only if:flowerbed[i] == 0
flowerbed[i-1] != 1
(ori == 0
)flowerbed[i+1] != 1
(ori == size-1
)
We skip the next plot after planting to maintain the no-adjacent rule.
β Code Snippet
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int count = 0;
int size = flowerbed.size();
for (int i = 0; i < size; i++) {
if (flowerbed[i] == 0) {
bool emptyLeft = (i == 0) || (flowerbed[i - 1] == 0);
bool emptyRight = (i == size - 1) || (flowerbed[i + 1] == 0);
if (emptyLeft && emptyRight) {
flowerbed[i] = 1;
count++;
if (count >= n) return true;
i++; // Skip next plot
}
}
}
return count >= n;
}
};
π§ͺ Example
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
We can place a flower at index 2 without violating the no-adjacent-flowers rule.
β±οΈ Time & Space
Time: O(n) β Single pass through the array
Space: O(1) β In-place modification
keep coding keep optimising π
Subscribe to my newsletter
Read articles from Abhinav Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Abhinav Kumar
Abhinav Kumar
π B.Tech CSE | π¨βπ» Learning DSA & C++ | π Building projects & writing what I learn | π Currently solving LeetCode & exploring Git/GitHub