Can Place Flowers

EasyGreedyLeetCode 605 ↗World 7-1
0:00 / 0:00

Plant a flower wherever both neighbours are empty, scanning left to right. Planting early never hurts, so stop as soon as n fit.

▼

The problem

LeetCode 605 (Easy). A flowerbed is an array of 0s (empty) and 1s (planted); flowers can't be in adjacent plots. Return true if n new flowers can be planted without breaking that rule.

Examples (LeetCode's): [1,0,0,0,1], n = 1 → true (plot 2 is the only plot with empty neighbours on both sides) and n = 2 → false (plots 1 and 3 each touch a flower).

TRY IT ON LEETCODE ▶

The solution

def can_place_flowers(flowerbed, n):
    count = 0
    for i in range(len(flowerbed)):
        left = i == 0 or flowerbed[i - 1] == 0
        right = i == len(flowerbed) - 1 or flowerbed[i + 1] == 0
        if flowerbed[i] == 0 and left and right:
            flowerbed[i] = 1
            count += 1
            if count >= n:
                return True
    return count >= n

Transcript

Can Place Flowers. A flowerbed is a row of plots: zero means empty, and one means a flower is already growing there. No two flowers can sit in neighboring plots. Can you plant n more?

Take one, zero, zero, zero, one, and ask for one flower. Plot one sits right next to a flower. Plot two has an empty plot on each side, so plant it there: true. Now ask for two. Plots one and three both touch a flower, so there's no room left: false.

The slow way is to try every set of empty plots, and check that no two flowers touch. Zero, zero, one, zero, zero has four empty plots, so that's sixteen sets. With k empty plots, it's two to the k.

The key idea is greedy. Walk from left to right, and plant whenever a plot and both its neighbors are empty. Past either end counts as empty. Why plant early? A flower here only blocks the next plot, because the one before it is already behind you. Planting one step later would take that plot and block the one after it. So planting early never hurts.

In code, start a count at zero. For each plot, check the left and right neighbors, treating the ends as empty. If all three are free, plant a flower and count it. As soon as the count reaches n, return true.

Now zero, zero, one, zero, zero, with n equal to two. Plot zero is open to the edge: plant, count one. Plot one now touches that new flower. Plot two is taken, and plot three touches it. Plot four is free all the way to the end: plant, count two. That reaches n, so it's true.

Each plot is checked once, in a single pass, so the time is linear. We only keep a counter, so the extra space is constant.

Look both ways, plant early, stop at n. That's Can Place Flowers.