algoadvance

Leetcode 605. Can Place Flowers

Problem Statement

You have a long flowerbed in which some 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.

Example 1:

Example 2:

Clarifying Questions

  1. Can the flowerbed array be empty?
    • No, according to the problem statement, it’s always provided as non-empty.
  2. What should be the output if n is 0?
    • The output should be true since we don’t need to plant any flowers.
  3. What constraints are placed on the values in the flowerbed array?
    • The flowerbed array will only contain 0’s and 1’s.

Strategy

  1. Iterate Through the Flowerbed:
    • Iterate through each position in the flowerbed.
  2. Check Planting Conditions:
    • For each element, check if the current plot is 0 and its adjacent plots (left and right) are also 0 or out of bounds of the array.
  3. Plant a Flower if Possible:
    • If the position meets the criteria, plant a flower there (set the position to 1) and decrease the count of n.
  4. Check Completion:
    • If at any point n reaches 0, return true.
  5. Return the Result:
    • After completing the loop, if n is still greater than 0, return false.

Code

public class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int length = flowerbed.length;
        
        for (int i = 0; i < length && n > 0; i++) {
            if (flowerbed[i] == 0) {
                boolean emptyLeft = (i == 0) || (flowerbed[i - 1] == 0);
                boolean emptyRight = (i == length - 1) || (flowerbed[i + 1] == 0);
                
                if (emptyLeft && emptyRight) {
                    flowerbed[i] = 1;
                    n--;
                }
            }
        }
        
        return n <= 0;
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI