Skip to content

Latest commit

 

History

History
65 lines (45 loc) · 2.91 KB

605.Can_Place_Flowers(Easy).md

File metadata and controls

65 lines (45 loc) · 2.91 KB

605. Can Place Flowers (Easy)

Date and Time: Sep 14, 2024, 21:44 (EST)

Link: https://leetcode.com/problems/can-place-flowers/


Question:

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.


Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1

Output: true

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2

Output: false


Constraints:

  • 1 <= flowerbed.length <= 2 * 10^4

  • flowerbed[i] is 0 or 1.

  • There are no two adjacent flowers in flowerbed.

  • 0 <= n <= flowerbed.length


Walk-through:

We can just append two extra [0] before and after flowerbed, so we can check flowerbed[i-1], flowerbed[i], flowerbed[i+1], if they are all 0, which means we can plant a flower and decrement n. Finally, we return n <= 0, so we know whether we can plant n flowers or not.


Python Solution:

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        # For each i in flowerbed, check itself and if its neighbors are 0, if so, replace 0 to be 1 and decrement n
        # Finally, check if n <= 0 to know if we can place flowers

        # 0 [1,0,0,0,1] 0
        
        # TC: O(n), n=len(flowerbed), SC: O(1)
        flowerbed = [0] + flowerbed + [0]
        for i in range(1, len(flowerbed)-1):
            if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
                n -= 1
                flowerbed[i] = 1
        return n <= 0

Time Complexity: $O(n)$, n is the length of flowerbed.
Space Complexity: $O(1)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms