#605

Can Place Flowers

Easy
ArrayGreedyGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a single pass through the flowerbed, counting how many flowers can be planted without checking adjacent plots repeatedly. This is more efficient and straightforward.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize a count for flowers planted and a variable to track the last position of a planted flower.
  2. 2Step 2: Iterate through the flowerbed array.
  3. 3Step 3: For each empty plot, check if it can be planted based on the last planted position.
  4. 4Step 4: If it can be planted, update the last planted position and increment the count.
  5. 5Step 5: If the count of planted flowers reaches n, return true.
  6. 6Step 6: After the loop, return false if n is not met.
solution.py11 lines
1def canPlaceFlowers(flowerbed, n):
2    count = 0
3    last_position = -2
4    for i in range(len(flowerbed)):
5        if flowerbed[i] == 0 and i - last_position > 1:
6            flowerbed[i] = 1
7            last_position = i
8            count += 1
9            if count >= n:
10                return True
11    return count >= n

Complexity note: This approach runs in O(n) time because we only make a single pass through the flowerbed array, checking each plot once.

  • 1Understanding the constraints of adjacent plots is crucial for determining valid planting positions.
  • 2Efficiently tracking the last planted position can reduce unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.