Flower placement and directory deletion
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked May 2026. It tests arrays, greedy and trees.
Two short, independent problems in one round.
Part 1: plant flowers
A row of plots is given as a list of 0s (empty) and 1s (already planted). No two flowers may be in adjacent plots. Decide whether n more flowers can be planted without breaking the rule.
Unless you agree on a different interface with the interviewer, assume:
-
can_place_flowers(plots: list[int], n: int) -> bool— the existing plots never break the rule.
can_place_flowers([1,0,0,0,1], 1) -> True # plant in the middle
can_place_flowers([1,0,0,0,1], 2) -> False
can_place_flowers([0,0,1,0,0], 2) -> True # both ends
Part 2: delete a directory tree
Given a file system API, delete a directory together with everything inside it. The API's delete call only removes a file or an empty directory.
-
fs.list(path) -> list[str]— the names inside a directory. fs.is_dir(path) -> bool-
fs.delete(path) -> None— removes a file or an empty directory; raises otherwise. - Write
delete_tree(fs, path) -> None.
/data
a.txt
logs/
1.log
old/
delete_tree(fs, "/data")
# deletes a.txt, 1.log, old/, logs/, then /data (children before their parent)
Constraints
- Part 1: up to 2 * 10^4 plots.
- Part 2: up to 10^6 entries; the tree can be very deep.
Clarifying questions
- Part 1: may I change the input list? Is
n = 0always true? - Part 2: are there symbolic links? Should the function follow them?
- Part 2: what should happen if one delete fails: stop, or keep going and report?
- Part 2: can other processes add files while we delete?
What a strong answer covers
- Part 1: a greedy left-to-right pass that plants wherever both neighbours are empty (treating the ends as empty), stopping early once
nis reached.O(n)time, and why greedy is optimal. - Part 2: a post-order traversal, children before the parent. An explicit stack instead of recursion for deep trees.
- Not following symlinks to directories, so the function never deletes outside the tree.
- Error handling: collect failures, retry, and report what was left behind.
- Tests: empty directory, a single file path, a deep chain, a failure in the middle.
Follow-ups
- Part 2 on a remote file system where each call is slow: delete in parallel safely.
- Make Part 2 resumable after a crash.
- Part 1 with a minimum gap of
kplots between flowers.
Where it's asked
- Google · Onsite coding · Last asked May 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
