Back to blog
Dec 10, 2024
2 min read

LeetCode 605: Can Place Flowers

Leetcode 605: Can Place Flowers solution in Python

Problem Description

LeetCode Problem 605

You have a long flowerbed in which some of the 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 true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

 

Example 1:

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

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2 Output: false

 

Constraints:

  • 1 <= flowerbed.length <= 2 * 104
  • flowerbed[i] is 0 or 1.
  • There are no two adjacent flowers in flowerbed.
  • 0 <= n <= flowerbed.length

Difficulty: Easy

Tags: array, greedy

Rating: 84.70%

Solution

Here’s my Python solution to this problem:

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        cnt = 0

        for i in range(len(flowerbed)):
            if flowerbed[i] == 0:
                left_empty = (i == 0) or (flowerbed[i-1] == 0)
                right_empty = (i == len(flowerbed)-1) or (flowerbed[i+1] == 0)

                if left_empty and right_empty:
                    cnt += 1
                    flowerbed[i] = 1

        return cnt >= n

Complexity Analysis

The solution has the following complexity characteristics:

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(1)O(1)

Note: This is an automated analysis and may not capture all edge cases or specific algorithmic optimizations.