EASY Greedy

605. 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.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Greedy reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Greedy: place flower whenever possible
  • โ†’ Check if current position and neighbors are empty
  • โ†’ For edge positions, only check one neighbor
  • โ†’ Time: O(n), Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขGreedy: place flower whenever possible
  • โ€ขCheck if current position and neighbors are empty
  • โ€ขFor edge positions, only check one neighbor

Common Pitfalls

  • โ€ขTime: O(n), Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
canPlaceFlowers([1,0,0,0,1], 1);
Expected:
false
Test Case 2
Not run
Input:
canPlaceFlowers([1,0,0,0,1], 2);
Expected:
false
Test Case 3
Not run
Input:
canPlaceFlowers([0], 1);
Expected:
false

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit