This is the 4th problem in Leetcode75 ( Array&Hashing ).
Problem Statement
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
Solution Strategy
- we're going to modify the array of flowers, by adding 0 at first index and at the last index.
- then we're going to iterate through the modified array with pointer, starting from 1 ( since the first element is definitely 0, cuz we just inserted that ).
- on each iteration we're gonna check if the current element in the array is 0, and we're also checking the previous element of current index and the next element also 0, if so, then we're going to place the flower there by changing the current element to 1, and and we move the pointer by 2 steps, then substracting the n numbers of flower that will be placed
- then if no such conditions met, we're just going to increase the pointer value to iterate to the next indices
- then after the while loop, we're going to return if the placed flowers equal to zero, since we have to return a boolean.
code:
class Solution {
func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool {
var modifiedArray = flowerbed
var pointer = 1
var totalFlowers = n
modifiedArray.insert(0, at: modifiedArray.startIndex)
modifiedArray.insert(0, at: modifiedArray.endIndex)
while pointer < modifiedArray.count - 1 && totalFlowers > 0 {
if modifiedArray[pointer] == 0 && modifiedArray[pointer-1] == 0 && modifiedArray[pointer+1] == 0 {
modifiedArray[pointer] = 1
pointer += 2
totalFlowers -= 1
} else {
pointer += 1
}
}
return totalFlowers == 0
}
}
Top comments (0)