Assign Gardener Colors So No Two Neighboring Gardens Match
Last updated: November 29, 2026
Quick Overview
There are n gardens and a list of bidirectional paths, and each garden touches at most three others. Assign each garden one of four flower types so that no two connected gardens share a type, and return any valid assignment.
0
0
0 solved
There are n gardens and a list of bidirectional paths, and each garden touches at most three others. Assign each garden one of four flower types so that no two connected gardens share a type, and return any valid assignment.
A technical screen question that looks like graph coloring, a classically hard problem, but the degree bound makes it easy. The interviewer at Google is checking whether you read the constraint carefully and turn it into a simple greedy argument.
What the Interviewer Expects
- Notice that max degree 3 with 4 colors guarantees a free color
- Build an adjacency list
- Greedily color nodes in any order
- Explain why no backtracking is needed
- Handle disconnected gardens
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if the max degree is 4 and you still have 4 colors?
- How would you minimize the number of colors used?
- How does this relate to assigning frequencies to neighboring cell towers?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
n,pathsas pairs of 1-based garden ids. - Each garden has degree at most 3.
- Output: list
answhereans[i]is in 1..4 and neighbors differ....
High-Level Design
General graph coloring with colors is NP-hard, but a graph with maximum degree can always be greedily colored with colors. Here and we have 4 colors. When we rea...