[
array
groupby
]
Leetcode 0605. Can Place Flowers
https://leetcode.com/problems/can-place-flowers
Let us consider several cases and underatand, what is going on:
- Case, when we have empty cases in the start (or end), like
1..
,01..
,001..
,0001..
,00001..
, … We can notice, that if we havek
zeroes, than we can put no more thank//2
flowers. - Case in the middle, like
..11..
,..101..
,..1001..
,..10001..
,..100001..
: in this case we can notice, tha we can put no more than(k-1)//2
flowers in each group.
How to handle this two groups so they work in the same way? Add 0
to the beginning and to the end of our flowerbed
. Next step is to use groupby
: which will evaluate lengths of each group. Finally, we choose only even
element from our list of lengths, for each element evaluate (i-1)//2
maximum number of flowers we can plant into this group, sum them and check if this number is more or equal to n
.
Complexity: time complexity is O(n)
, space complexity is also O(n)
.
class Solution:
def canPlaceFlowers(self, flowerbed, n):
t = [len(list(j)) for i, j in groupby([0] + flowerbed + [0])]
return sum((i-1)//2 for i in t[0::2]) >= n
If you like the solution, you can upvote it on leetcode discussion section: Problem 0605