EasyNo. 0605

Can Place Flowers — LeetCode 605 Python Solution

Pattern
Greedy
Topics
Greedy, Array
On a study list
LeetCode 75
Reading time
2 min

The problem

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.

Example

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

Python solution

PythonSolution
class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        flowerbed = [0] + flowerbed + [0]
        for i in range(1, len(flowerbed) - 1):
            if sum(flowerbed[i - 1 : i + 2]) == 0:
                flowerbed[i] = 1
                n -= 1
        return n <= 0

Complexity

Time
O(n)where n is the length of the array flowerbed
Space · auxiliary
O(1)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 605. Can Place Flowers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0611Valid Triangle NumberMedium
0011Container With Most WaterMedium
0134Gas StationMedium
0135CandyHard
0179Largest NumberMedium
0324Wiggle Sort IIMedium

Frequently asked questions

How hard is LeetCode 605. Can Place Flowers?

LeetCode 605. Can Place Flowers is rated Easy on LeetCode.

What is the time complexity of LeetCode 605. Can Place Flowers?

The Python solution on this page runs in O(n), where n is the length of the array flowerbed.

What is the space complexity of LeetCode 605. Can Place Flowers?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 605. Can Place Flowers cover?

LeetCode 605. Can Place Flowers is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.