Can Place Flowers

A long flowerbed is given as an array of 0s (empty plot) and 1s (planted plot). Flowers cannot be planted in adjacent plots. Given the flowerbed and an integer n, return true if n new flowers can be planted without breaking the no-adjacent-flowers rule, and false otherwise.

30:00

Can Place Flowers
easy
Free written solution
Topics
Companies

A long flowerbed is given as an array of 0s (empty plot) and 1s (planted plot). Flowers cannot be planted in adjacent plots. Given the flowerbed and an integer n, return true if n new flowers can be planted without breaking the no-adjacent-flowers rule, and false otherwise.

Example 1:
Input: {"flowerbed":[1,0,0,0,1],"n":1}
Output: true
Constraints:
  • 1≤flowerbed.length≤2×1041 \leq \text{flowerbed.length} \leq 2 \times 10^4

  • flowerbed[i]\text{flowerbed}[i] is 00 or 11.

  • There are no two adjacent flowers in flowerbed.

  • 0≤n≤flowerbed.length0 \leq n \leq \text{flowerbed.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"flowerbed":[1,0,0,0,1],"n":1}

We need to fit 1 new flower. Walk the bed left to right and plant in every empty plot whose neighbors are both empty.

flowerbed

0

1

2

3

4

already planted

newly planted

neighbor empty

neighbor blocks

New flowers needed

count = 0 / n = 1

Variables
VariableValue
count0
n1
DepthFunction Call
Stack empty
0/5