← All problems

4. Can Place Flowers

EasyArray / StringOriginal on LeetCode ↗

A row of plots is described by flowerbed, where 1 means the plot already has a flower and 0 means it is empty. Flowers can't grow in two neighbouring plots.

Can you plant n more flowers without breaking that rule? Return True or False. The input never already breaks the rule.

Constraints

  • 1 <= len(flowerbed) <= 20000
  • flowerbed[i] is 0 or 1, and no two 1s are next to each other
  • 0 <= n <= len(flowerbed)

Examples

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

Hints

Hint 1

Go left to right. A spot works if it is empty and both neighbours (or the edge) are empty.

Hint 2

Plant greedily as soon as a spot works; planting early never makes things worse.

Python 3

Run checks the examples · Submit checks every test. The first run downloads Python (about 10 MB) and takes a few seconds.