LeetCode 605: Can Place Flowers

link

Time: \mathcal{O}(n), space: \mathcal{O}(1).

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        i = 0
        while i < len(flowerbed) and n > 0:
            if flowerbed[i] == 1:
                i += 1
                continue
            has_flower_on_left = i > 0 and flowerbed[i-1] == 1
            if has_flower_on_left:
                i += 1
                continue
            has_flower_on_right = i < len(flowerbed)-1 and flowerbed[i+1] == 1
            if has_flower_on_right:
                i += 1
                continue
            
            # plant
            flowerbed[i] = 1
            n -= 1
            i += 1
        return n == 0

Leave a comment