Python 1042.py
class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
# store "forward-only" connections
next = [ [] for _ in range(n) ]
for x, y in paths:
next[min(x, y) - 1].append(max(x, y) - 1) # problem has 1-based indexing, Python prefers 0-based
# if there are 4 types of flowers and at most 3 neighbors
# then there will always be a flower not used yet by the neighbors
used = [ 0 ] * n
for i in range(n):
blocked = used[i]
# find lowest bit which is 0
mask = 1
flower = 1
while mask & blocked:
mask <<= 1
flower += 1
# spread mask
for j in next[i]:
used[j] |= mask
yield flower
Difficulty
and has an acceptance rate of about 54% (100k+ submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Depth First Search
- Graph Theory
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the garden-flower assignment problem by iterating through the gardens in a deterministic order and assigning the smallest possible flower type that does not conflict with already assigned neighboring gardens. It leverages a forward-only adjacency representation and bit-masking to keep track of flower usage efficiently. The algorithm guarantees a valid assignment because the problem constraints ensure that each garden has at most three neighbors while only four flower types exist.
Core Steps
Building a forward-only adjacency list
The first phase converts the list of bidirectional paths into a structure that records only connections from a lower-indexed garden to a higher-indexed one. This eliminates the need to process each edge twice.
next = [ [] for _ in range(n) ]
for x, y in paths:
next[min(x, y) - 1].append(max(x, y) - 1) # convert to 0-based indexing
By storing only the “forward” edges, the algorithm can propagate flower constraints in a single pass without revisiting already processed gardens.
Maintaining used-flower masks
A list named used holds an integer mask for each garden. Each bit in the mask corresponds to a flower type that has been blocked by a neighbor that has already been assigned. Initially all masks are zero.
used = [ 0 ] * n
Selecting the smallest available flower
For each garden i, the current mask blocked is read from used[i]. The algorithm then scans the bits from the least significant upward until it finds a zero bit, which indicates the smallest flower type not yet blocked.
blocked = used[i]
mask = 1
flower = 1
while mask & blocked:
mask <<= 1
flower += 1
The variables mask and flower progress in lockstep: mask holds the bit representation of the chosen flower, while flower holds its 1-based identifier.
Propagating the chosen flower to forward neighbors
After determining the flower for garden i, the corresponding bit mask is OR-ed into the used entry of each forward neighbor. This marks the flower as unavailable for those neighbors when they are processed later.
for j in next[i]:
used[j] |= mask
Yielding the result
The algorithm yields the selected flower type for each garden in order, producing the final list of assignments.
yield flower
Because the generator yields values sequentially, the caller can easily collect them into a list.
Edge Cases Handled
When the input contains no paths, the adjacency list consists of empty sub-lists, and each garden’s used mask remains zero. The while-loop therefore selects flower 1 for every garden, which is valid because there are no adjacency constraints.
If a garden has fewer than three neighbors, the bit-mask logic still works correctly: only the bits corresponding to already assigned neighboring flowers are set, and the search for the first zero bit naturally skips over any absent constraints.
The conversion from 1-based to 0-based indexing ensures that gardens numbered from 1 to n map correctly to Python list indices, preventing off-by-one errors even when the input contains the maximum garden number.
When multiple edges connect the same pair of gardens, the forward-only list may contain duplicate entries. The OR-operation on the neighbor’s mask is idempotent, so repeated propagation of the same mask does not affect correctness.
Performance Optimizations
The use of a forward-only adjacency list reduces the number of edge traversals by half compared with a fully bidirectional representation. Each edge is examined exactly once when its source garden is processed, eliminating redundant work.
Bit-masking replaces a set or list of used flower identifiers with a single integer per garden. Checking whether a flower is blocked becomes a single bitwise AND operation, and marking a flower as blocked for a neighbor is a single bitwise OR. These operations are constant-time and highly cache-friendly.
The while-loop that finds the first zero bit iterates at most four times because only four flower types exist. This bounded loop guarantees fast selection without the overhead of more complex data structures.
By yielding results directly rather than constructing an intermediate list, the implementation can stream the output, which may reduce peak memory usage when the caller consumes the generator incrementally.
ELI5 - Simplified Explanation
Imagine a big garden with many patches where you want to plant pretty flowers. Each patch is connected to other patches by little garden paths. The rule is that if two patches are connected by a path, they must have different types of flowers. You have four different colors of flowers to pick from.
The computer starts by looking at all the paths to see which patches are neighbors. It keeps a list of these connections so it knows exactly where each path goes. Then, it walks through every patch one by one to decide which flower to plant.
For each patch, it looks at all the neighbors to see if any flowers have already been picked. It keeps track of which colors are taken so it never picks a color that a neighbor already has. Because there are four colors to choose from and each patch only has a few neighbors, there is always at least one color left over that is safe to use. It picks that safe color, plants the flower, and tells the neighbors that this color is now taken so they remember not to use it. This happens for every single patch until the whole garden is colorful and happy.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1081: Smallest Subsequence of Distinct Characters
- problem 1104: Path In Zigzag Labelled Binary Tree
- problem 1192: Critical Connections in a Network
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality