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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Easy

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
graph coloring
greedy
adjacency list
degree bound
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • Input: n, paths as pairs of 1-based garden ids.
  • Each garden has degree at most 3.
  • Output: list ans where ans[i] is in 1..4 and neighbors differ....
High-Level Design

General graph coloring with kk colors is NP-hard, but a graph with maximum degree Δ\Delta can always be greedily colored with Δ+1\Delta + 1 colors. Here Δ=3\Delta = 3 and we have 4 colors. When we rea...


Submit Your Answer
Markdown supported