Can Place Flowers


Editoral is clean and easy to understand. One optimization: when you plant a flower, you can increment i by 2 (you can never plant two beside each other).
In my solution I added flowers from both the start and end of array during each loop iteration  same worse case scenario but better for some input arrays.


Both answers modify the input array. I don't think that should be allowed. Here is my solution.
class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
if not flowerbed:
return False
if n ==0:
return True
spots = 0
length = len(flowerbed)1
i=0
while i <= length:
spot_found = Falseif not flowerbed[i]==0: i+=1 continue elif i==0: if i+1 <=length: if flowerbed[i+1]==0: spot_found = True else: spot_found = True elif i==length: if not i1 < 0: if flowerbed[i1] == 0: spot_found = True else: spot_found = True else: if flowerbed[i1] == flowerbed[i+1] == 0: spot_found = True if spot_found: spots+=1 i+=2 # go to the next possible spot. Reserve this one if spots>=n: return True else: i+=1 #go to the next possible spot. return False

For the inputs [0] and 2, the online judge gives the following "Expected answer":
Line 6: bool Solution::canPlaceFlowers(std::vector<int>&, int): Assertion `n <= (int)flowerbed.size() && n >= 0 && (int)flowerbed.size() > 0' failed.
Given the constraint where the input is not allowed to be modified, here's my Java solution:
class Solution { public boolean canPlaceFlowers(int[] flowerBed, int numFlowersToAdd) { if(numFlowersToAdd == 0) { return true; } if(numFlowersToAdd < 0  flowerBed == null  flowerBed.length == 0) { return false; } int maxFlowersCanPlant = 0; int firstZeroIndex = 1; // Index of the last zero we've found boolean foundZero = flowerBed[0] == 0 ? true : false; for(int i=1; i<flowerBed.length; i++) { if(flowerBed[i] == 0) { if(!foundZero) { firstZeroIndex = i; } foundZero = true; } else { // We found a 1 if(foundZero) { maxFlowersCanPlant += (ifirstZeroIndex1)/2; } foundZero = false; } } // There are trailing zeros if(firstZeroIndex < flowerBed.length && flowerBed[flowerBed.length1] == 0) { firstZeroIndex; maxFlowersCanPlant += (flowerBed.lengthfirstZeroIndex1)/2; } return maxFlowersCanPlant >= numFlowersToAdd; } }