Can Place Flowers: A Simple Greedy Solution

🌸 Day 26 of #100DaysOfCode – LeetCode Problem #605: Can Place Flowers 🧩 Problem: You have a flowerbed represented as an array of 0s and 1s. 0 means empty, 1 means a flower is already planted. Flowers cannot be planted in adjacent plots. Given n, can you plant n new flowers without violating the rule? 💡 Approach: Iterate through the array. For each empty plot, check if its neighbors are empty (or it's on the boundary). If safe, plant a flower and decrease n. If n reaches 0, return true; otherwise, false. 💻 Java Code: class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { for (int i = 0; i < flowerbed.length; i++) { if (flowerbed[i] == 0) { boolean emptyLeft = (i == 0) || (flowerbed[i-1] == 0); boolean emptyRight = (i == flowerbed.length - 1) || (flowerbed[i+1] == 0); if (emptyLeft && emptyRight) { flowerbed[i] = 1; n--; if (n == 0) return true; } } } return n <= 0; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) This problem is a neat reminder that sometimes, simple greedy checks beat complicated algorithms. 

To view or add a comment, sign in

Explore content categories