Can Place Flowers

Easy Greedy

Problem

Given an integer array flowerbed containing 0's and 1's, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

  • 1 ≤ flowerbed.length ≤ 2 * 10⁴
  • flowerbed[i] is 0 or 1
  • There are no two adjacent flowers in the initial flowerbed
  • 0 ≤ n ≤ flowerbed.length

Example

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

The flowerbed has empty plots at indices 1, 2, and 3. The algorithm scans from left to right. At index 1, the left neighbor is occupied (index 0), so it cannot plant here. At index 2, both neighbors (indices 1 and 3) are empty, so it plants a flower here, reducing n from 1 to 0. Since n reaches 0, the algorithm returns true immediately, confirming that planting is possible without violating adjacency.

Approach

Straightforward Solution

A brute-force approach might try all combinations of planting flowers, checking adjacency after each attempt, which is exponential and infeasible for large inputs.

Core Observation

The fundamental truth is that a flower can only be planted in a plot if both its immediate neighbors are empty or out of bounds (for edge plots). This local condition ensures no two flowers are adjacent.

Path to Optimal

The key insight is to greedily plant flowers at the earliest possible empty plot that satisfies the adjacency condition. By scanning left to right and planting whenever possible, the algorithm maximizes the number of flowers planted without violating the rule. This greedy approach works because planting earlier frees up more space later and never blocks a better future placement.

Optimal Approach

Iterate through the flowerbed array. For each empty plot, check if the left and right neighbors are empty or out of bounds. If so, plant a flower by setting the plot to 1 and decrement n. If at any point n reaches zero, return true immediately. After the loop, return whether n is less than or equal to zero.

Time

O(m)

The algorithm performs a single pass through the flowerbed array of length m, checking neighbors and updating state in constant time per element.

Space

O(1)

The algorithm modifies the input array in place and uses only a fixed number of variables, resulting in constant auxiliary space.

Pattern Spotlight

Greedy (Local Optimal Placement)

When constraints depend only on immediate neighbors, a left-to-right greedy scan that plants at the first valid spot ensures maximum placements without violating adjacency.

Solution

1class Solution:
2 def canPlaceFlowers(self, flowerbed: list[int], n: int) -> bool:
3 for i in range(len(flowerbed)):
4 if flowerbed[i] == 0:
5 left_empty = i == 0 or flowerbed[i - 1] == 0
6 right_empty = i == len(flowerbed) - 1 or flowerbed[i + 1] == 0
7
8 if left_empty and right_empty:
9 flowerbed[i] = 1
10 n -= 1
11
12 if n == 0:
13 return True
14
15 return n <= 0

Step-by-Step Solution

1

Scan Flowerbed and Greedily Plant Flowers at Valid Positions

3for i in range(len(flowerbed)):
4 if flowerbed[i] == 0:
5 left_empty = i == 0 or flowerbed[i - 1] == 0
6 right_empty = i == len(flowerbed) - 1 or flowerbed[i + 1] == 0
8 if left_empty and right_empty:
9 flowerbed[i] = 1
10 n -= 1
12 if n == 0:
13 return True

Objective

To iterate through the flowerbed and plant flowers greedily at plots where both neighbors are empty or out of bounds, decrementing n accordingly.

Key Insight

By checking the left and right neighbors for each empty plot, the algorithm ensures no adjacency violation occurs. Planting immediately when possible maximizes the number of flowers planted because it prevents missing early opportunities that could block later placements. This local decision-making is sufficient because the problem's constraints are strictly local (adjacent plots only).

Interview Quick-Check

Core Logic

The algorithm checks if the current plot is empty and both neighbors are empty or out of bounds, then plants a flower and decrements n.

State & Boundaries

Edge plots are handled by treating out-of-bound neighbors as empty, allowing planting at the ends if valid.

Common Pitfalls & Bugs

Failing to update the flowerbed array after planting can cause incorrect multiple plantings in the same spot.

Complexity

The single pass with constant-time neighbor checks ensures O(m) time and O(1) space.

2

Return Whether All Flowers Were Successfully Planted

15return n <= 0

Objective

To return true if all required flowers have been planted (n <= 0), otherwise false.

Key Insight

If the loop completes without returning true, it means not all flowers could be planted. Returning n <= 0 covers the case where n was zero or negative after planting, confirming success. This final check ensures correctness for all inputs.

Interview Quick-Check

Core Logic

Returning n <= 0 confirms whether the planting goal was met after scanning the entire flowerbed.

State & Boundaries

This return handles cases where n is initially zero or becomes zero during iteration.

Line Analysis

This solution has 2 Critical lines interviewers watch for.

Line 8 Critical
if left_empty and right_empty:

Check if both left and right neighbors are empty or out of bounds, allowing planting.

This condition enforces the no-adjacent-flowers rule by ensuring planting does not violate adjacency constraints.

Line 9 Critical
flowerbed[i] = 1

Plant a flower at the current plot by setting it to 1.

Updating the flowerbed array prevents future iterations from planting adjacent flowers, maintaining correctness.

Line 5 Core
left_empty = i == 0 or flowerbed[i - 1] == 0

Determine if the left neighbor is empty or out of bounds (for the first plot).

Treating out-of-bound neighbors as empty simplifies boundary conditions and allows planting at the edges when valid.

Line 6 Core
right_empty = i == len(flowerbed) - 1 or flowerbed[i + 1] == 0

Determine if the right neighbor is empty or out of bounds (for the last plot).

Symmetric to the left neighbor check, this ensures correct handling of the right edge of the flowerbed.

Line 12 Core
if n == 0:

Check if all required flowers have been planted.

Early return improves efficiency by stopping the scan once the planting goal is achieved.

Line 13 Core
return True

Return true immediately when planting goal is met.

This terminates the function early, confirming success without unnecessary further checks.

Line 4 Core
if flowerbed[i] == 0:

Check if the current plot is empty (0).

Only empty plots can potentially accommodate new flowers, so this condition filters candidate positions.

Line 10 Core
n -= 1

Decrement the number of flowers left to plant.

Tracking the remaining flowers to plant allows early termination when the goal is met.

Line 15 Core
return n <= 0

Return true if all flowers were planted, false otherwise.

This final return ensures the function correctly reports failure if the planting goal was not met during iteration.

Line 3 Standard
for i in range(len(flowerbed)):

Iterate through each plot in the flowerbed array.

A single pass through the flowerbed is sufficient because planting decisions depend only on local neighbors, enabling a greedy approach.

Test Your Understanding

Why does greedily planting flowers at the earliest valid spot guarantee the maximum number of flowers planted without adjacency violations?

Because planting at the earliest valid spot never blocks future valid spots that could accommodate more flowers, ensuring no opportunity is wasted and the maximum number of flowers is planted.

Related Problems

Greedy pattern

Don't just read it. Drill it.

Reconstruct Can Place Flowers from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Can Place Flowers drill

or drill a free problem