โ† Back to Index

๐Ÿ“š Can Place Flowers โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Can Place Flowers problem involves determining whether it is possible to plant a given number of flowers in a flowerbed without violating the rule that no two flowers can be adjacent.

๐Ÿงฑ Pattern Template

Greedy Algorithm

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 0;

        for (int i = 0; i < flowerbed.length; i++) {
            if (flowerbed[i] == 0 &&
                (i == 0 || flowerbed[i - 1] == 0) &&
                (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                flowerbed[i] = 1; // Plant a flower
                count++;
            }

            if (count >= n) {
                return true; // Enough flowers planted
            }
        }

        return count >= n; // Check if we could plant enough flowers
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true

Explanation:
- Plant a flower at index 2. The flowerbed becomes [1,0,1,0,1].
- It is possible to plant 1 flower.

๐Ÿ’ก Pro Tips