Can Place Flowers

Plant new flowers in a row of plots so that no two flowers end up side by side.

A flowerbed is a row of plots, given as an array of 0s and 1s: 0 is an empty plot and 1 is a plot that already has a flower. Two flowers may never grow in plots that are next to each other. Given the flowerbed and a number n, return true if n new flowers can be planted without breaking that rule, and false otherwise.

Example 1
Input: flowerbed = [1, 0, 0, 0, 1], n = 1
Output: true
Explanation: the middle plot can take a flower.
Example 2
Input: flowerbed = [1, 0, 0, 0, 1], n = 2
Output: false
Example 3
Input: flowerbed = [0, 0, 1, 0, 0], n = 2
Output: true
Explanation: the first and the last plot can each take a flower.
Solution

The Idea

Think of a garden bed with a row of plots, numbered from 0 on the left. Plants need room, so a flower may only go where nothing grows right beside it. We are asked whether n more flowers fit.

Look at example 1, [1, 0, 0, 0, 1]. Plots 1, 2 and 3 are empty, so three flowers might seem to fit. But plot 1 is right next to the flower in plot 0, and plot 3 is right next to the one in plot 4. Only plot 2 has an empty plot on both sides. So one new flower fits, and two do not, which is example 2.

So a plot can take a flower when it is empty and both of its neighbours, the plots just left and right of it, are empty too. But the first and the last plot have only one neighbour each. What about the side with no plot at all?

Look at the picture, which shows example 3, [0, 0, 1, 0, 0]. Plot 2 holds an old flower, so plots 1 and 3 are next to a flower and stay empty. Plot 0 has plot 1 on its right and nothing on its left. Nothing beyond the end can hold a flower, so the outside counts as empty, and plot 0 takes a new flower. Plot 4 does the same at the other end, so two flowers fit.

The flowerbed [0, 0, 1, 0, 0] as five plots. Plot 2 holds an old flower, so plots 1 and 3 are next to a flower. Plots 0 and 4 have the outside beside them, which counts as empty, so they take the two new flowers.

One more thing changes as we plant: a new flower is a neighbour too. In [0, 0, 0] every plot looks free at first, yet after a flower goes into plot 0, plot 1 is next to it. Only plots 0 and 2 can be used, not all three.

So the plan is to walk along the row, plant in every plot that is free at that moment, and count the flowers.

Solution Approach

Turning that idea into code means settling three things: which free plots to plant in, how a new flower blocks its neighbour, and when to stop.

Which free plots to use

Is it safe to plant in the first free plot we meet, or could a different choice fit more flowers? The slow, sure way would be to try every possible set of empty plots and keep the largest that follows the rule. A row of 30 empty plots already has 230, over a billion, such sets.

Planting in the leftmost free plot is never worse. A flower in plot i blocks only plot i + 1 on its right, because everything to its left has already been decided. Any other plan that leaves plot i empty could move its next flower into plot i and still follow the rule. Taking the best-looking choice at each step like this is called a greedy approach.

Remembering new flowers

How does the next plot learn about a flower we just planted? We write a 1 into the array at that plot. When the walk reaches plot i + 1, it reads that 1 as its left neighbour, and skips the plot.

When to stop

Does the walk always have to reach the end? No. Once n flowers are planted, the rest of the bed does not matter, so the walk can stop there. If the walk reaches the end first, there was not room for all of them.

Java Solution

The method canPlaceFlowers works in these steps:

  1. Walk along the bed with a loop over the plots, from plot 0 to the last plot, len - 1.
  2. At each plot i, check both sides. leftFree is true when i is the first plot or the plot to its left is empty, and rightFree is true when i is the last plot or the plot to its right is empty.
  3. If the plot itself is empty and both sides are free, plant a flower there by setting flowerbed[i] = 1, so the next plot sees it as a neighbour, and take one off n, the flowers still to plant.
  4. Stop the loop as soon as n reaches 0, then return whether every flower was planted.

The main method runs the three examples, then a single empty plot, two empty plots that need two flowers, a fully empty bed and a request for no flowers at all. For each one it prints the bed, n, the answer and the bed afterwards.

Java
import java.util.Arrays;

public class CanPlaceFlowers {

    public static boolean canPlaceFlowers(int[] flowerbed, int n) {
        int len = flowerbed.length;
        for (int i = 0; i < len && n > 0; i++) {
            boolean leftFree = i == 0 || flowerbed[i - 1] == 0;        // no plot left of 0
            boolean rightFree = i == len - 1 || flowerbed[i + 1] == 0; // no plot right of the end
            if (flowerbed[i] == 0 && leftFree && rightFree) {
                flowerbed[i] = 1;             // plant here, the next plot sees it
                n--;
            }
        }
        return n <= 0;
    }

    static void run(int[] flowerbed, int n) {
        String before = Arrays.toString(flowerbed);
        boolean result = canPlaceFlowers(flowerbed, n);
        System.out.printf("%-16s n = %d -> %-5s  bed after: %s%n",
                before, n, result, Arrays.toString(flowerbed));
    }

    public static void main(String[] args) {
        run(new int[] {1, 0, 0, 0, 1}, 1);
        run(new int[] {1, 0, 0, 0, 1}, 2);
        run(new int[] {0, 0, 1, 0, 0}, 2);
        run(new int[] {0}, 1);                  // a single empty plot
        run(new int[] {0, 0}, 2);               // two plots, but they touch
        run(new int[] {0, 0, 0, 0, 0}, 3);      // a fully empty bed
        run(new int[] {1, 0, 1}, 0);            // nothing to plant
    }
}

Running it prints:

Output
[1, 0, 0, 0, 1]  n = 1 -> true   bed after: [1, 0, 1, 0, 1]
[1, 0, 0, 0, 1]  n = 2 -> false  bed after: [1, 0, 1, 0, 1]
[0, 0, 1, 0, 0]  n = 2 -> true   bed after: [1, 0, 1, 0, 1]
[0]              n = 1 -> true   bed after: [1]
[0, 0]           n = 2 -> false  bed after: [1, 0]
[0, 0, 0, 0, 0]  n = 3 -> true   bed after: [1, 0, 1, 0, 1]
[1, 0, 1]        n = 0 -> true   bed after: [1, 0, 1]

The first three lines answer the three examples: true, false and true. Look at the third line: the bed afterwards is [1, 0, 1, 0, 1], with new flowers in plots 0 and 4, just as in the picture. On the second line the walk plants in plot 2, reaches the end with one flower still to go, and returns false.

The fifth line is [0, 0] with n = 2. Plot 0 gets a flower, and the 1 written there makes plot 1 a neighbour of a flower, so the answer is false. Without that write, both plots would look free and the method would return true, although only one flower fits.

The last line asks for no flowers. The loop condition n > 0 is false from the start, so the method returns true and the bed is unchanged.

In the conditions, i == 0 || is checked first, so for plot 0 Java never reads flowerbed[i - 1], which would be index -1 and throw an exception. i == len - 1 || guards the right end the same way. Note also that the method changes the array it is given; pass a copy if the caller still needs the original.

The original implementation, CanPlaceFlowers.java, is on GitHub.

Complexity

The walk looks at each plot at most once, and at each plot it reads only the plot and its two neighbours.

  • Time: O(L), where L is the number of plots, the length of the array. Each plot costs a fixed number of steps, and the walk may stop early once enough flowers are planted.
  • Space: O(1). Apart from the array, the method keeps only len, the index i and two booleans, because it plants into the array itself instead of a copy.

Taking the earliest valid choice is also the greedy step in Assign Cookies.