πŸͺ΄Can Place Flowers - LeetCode 605

Abhinav KumarAbhinav Kumar
2 min read

🧠 Problem Summary

You're given a flowerbed (an array of 0s and 1s), where:

  • 0 β†’ empty plot

  • 1 β†’ 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 (or i == 0)

    • flowerbed[i+1] != 1 (or i == 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 πŸš€

0
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