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
๐ค Output