InterviewPrepKit

Home / Coding / Arrays & Hashing

Can Place Flowers

easy Original β†—
Solving tips
  • Placements only interact with immediate neighbors, so a left-to-right greedy is optimal: plant whenever the plot and both neighbors are 0.
  • Treat out-of-bounds as empty so edge plots (index 0 and last) are handled correctly.
  • When mutating a copy, check neighbors against the mutated array so a just-planted flower at i blocks i+1.
  • Target O(n) time, O(1) space; alternative is counting zero-runs where a run of L zeros holds (L-1)//2 flowers, and handle n==0 as trivially True.

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 = 1 β†’ True β€” the middle plot (index 2) has empty neighbors on both sides.
  • flowerbed = [1,0,0,0,1], n = 2 β†’ False β€” planting at index 2 uses up the only legal spot; no second spot remains.
  • flowerbed = [0,0,1,0,0], n = 1 β†’ True β€” 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)

The array length rules out anything worse than roughly linear work per plot β€” a single O(n) pass is the target.

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`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.