InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Can Place Flowers

easy Original ↗ 00:00

Problem

You are given a row of garden plots as an integer array flowerbed, where each entry is 1 (a flower is already planted there) or 0 (the plot is empty). Flowers cannot be planted in adjacent plots — every flower must have empty (or out-of-bounds) plots on both sides. The input already satisfies this rule.

Given an integer n, decide whether it is possible to plant n new flowers in the empty plots without ever violating the no-adjacent-flowers rule. Return True if it is possible, otherwise False.

Examples

  • flowerbed = [1,0,0,0,1], n = 1True — the middle plot (index 2) has empty neighbors on both sides.
  • flowerbed = [1,0,0,0,1], n = 2False — planting at index 2 uses up the only legal spot; no second spot remains.
  • flowerbed = [0,0,1,0,0], n = 1True — index 0 works because the left edge counts as empty.

Constraints

  • 1 <= len(flowerbed) <= 2 * 10^4
  • flowerbed[i] is 0 or 1, with no two adjacent 1s
  • 0 <= n <= len(flowerbed)

With the length capped at 2 * 10^4, aim for a single O(n) pass.

Think about it first

Hint 1 Look at one empty plot in isolation. What exactly must be true of its two neighbors for it to accept a flower? What happens at the two ends of the bed?
Hint 2 If a plot is plantable when you reach it scanning left to right, can skipping it ever help you plant MORE flowers later? Think about what planting there "blocks".
Hint 3 Scan left to right; whenever the current plot is 0 and both neighbors are 0 (treating out-of-bounds as 0), plant immediately and count it. Compare the count to `n`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug