Last active
September 28, 2025 21:29
-
-
Save mfaani/f3d555677410b7151a20c785d0de04c9 to your computer and use it in GitHub Desktop.
#leetcode #swift #arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
Example 1: | |
Input: flowerbed = [1,0,0,0,1], n = 1 | |
Output: true | |
Example 2: | |
Input: flowerbed = [1,0,0,0,1], n = 2 | |
Output: false | |
*/ | |
class Solution { | |
func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool { | |
// just start planting at the first possible position... | |
// or maybe just count the number of gaps that have a space of 3 or 5 | |
// if node is 0, begin a potential bed. | |
// if node is 1, then reset it. | |
// if node potential bed's count - 1, then divided by 2 — I think. TBD | |
// if node is on the edge, the assume its neighbor is 0 | |
var total = 0 | |
var count = 1 // starting from 1, because the left side is assumed `0` | |
for i in 0..<flowerbed.count { | |
if flowerbed[i] == 0 { | |
foundEmpty() | |
} else { | |
foundFlower() | |
} | |
} | |
adjustLastCount() | |
return total >= n | |
func foundEmpty() { | |
count += 1 | |
} | |
func foundFlower() { | |
adjust() | |
count = 0 | |
} | |
func adjust() { | |
total += (count - 1) / 2 | |
} | |
// - NOTE: | |
// If last item is `1`, then it's already handled from the `for-loop`. | |
// If last item is `0`, then you must `increment` its value by `1`, because its right side is assumed as `0` | |
func adjustLastCount() { | |
count += 1 | |
adjust() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment