Can Place Flowers - Problem

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

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

Input & Output

Example 1 — Basic Case
$ Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
💡 Note: We can plant 1 flower at position 2. Position 1 is invalid (adjacent to flower at 0), position 3 is invalid (adjacent to flower at 4), but position 2 has empty neighbors on both sides.
Example 2 — Not Enough Space
$ Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
💡 Note: We can only plant 1 flower at position 2. There's no second valid position that doesn't violate the adjacency rule, so we cannot plant 2 flowers.
Example 3 — Edge Case All Empty
$ Input: flowerbed = [0,0,0], n = 2
Output: true
💡 Note: We can plant flowers at positions 0 and 2. Position 1 cannot be used because it would be adjacent to both planted flowers.

Constraints

  • 1 ≤ flowerbed.length ≤ 2 × 104
  • flowerbed[i] is 0 or 1
  • There are no two adjacent flowers in flowerbed
  • 0 ≤ n ≤ flowerbed.length

Visualization

Tap to expand
Can Place Flowers - Greedy Approach INPUT Flowerbed Array: 1 [0] 0 [1] 0 CAN PLANT [2] 0 [3] 1 [4] flowerbed = [1,0,0,0,1] n = 1 Need to plant 1 flower = Planted (1) = Empty (0) = Valid spot ALGORITHM STEPS 1 Initialize counter count = 0, i = 0 2 Scan each plot Check if current = 0 3 Check neighbors Left = 0 (or edge)? Right = 0 (or edge)? 4 Plant if valid Set plot to 1, count++ Greedy Trace: i=0: flowerbed[0]=1 skip i=1: left=1, cannot plant i=2: left=0, right=0 PLANT! i=3: left=1, cannot plant i=4: flowerbed[4]=1 skip FINAL RESULT After Planting: 1 0 1 NEW! 0 1 Output: true Planted 1 flower count (1) >= n (1) Verification: No adjacent flowers Rule satisfied - OK Key Insight: The greedy approach works because planting a flower as early as possible never blocks a better solution. At each empty plot, we check: Is left neighbor empty (or edge)? Is right neighbor empty (or edge)? If both conditions are true, plant immediately. Time: O(n), Space: O(1). No need for backtracking! TutorialsPoint - Can Place Flowers | Greedy - Plant Whenever Possible
Asked in
Google 15 Amazon 12 LinkedIn 8
34.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen