Python 1-line solution with explanation


  • 0
    P
    def canPlaceFlowers(self, flowerbed, n):
        return sum((len(zeros) - 1) // 2 for zeros in ("0" + "".join(map(str, flowerbed)) + "0").split("1") if zeros != "") >= n
    

    Key Observation

    In the middle of the list, "000" can provide one available position, and "00000" can provide two, and so on. Therefore each zeros segment. can provide (len(zeros) -1 ) // 2 positions.

    Corner Cases

    1. For the zeros in the list edge, it only takes "00" to provide a position. However, we can align the rule by padding "0" in both ends of the list.

    2. We have to exclude the case that zeros == "", that happens at splitting two adjacent ones "11", since (0 -1) // 2 = -1 violate the general rule.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.