Leetcode #1042: Flower Planting With No Adjacent
In this guide, we solve Leetcode #1042 Flower Planting With No Adjacent in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Depth-First Search, Breadth-First Search, Graph
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: n = 3, paths = [[1,2],[2,3],[3,1]]
Output: [1,2,3]
Explanation:
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].
Python Solution
class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
g = defaultdict(list)
for x, y in paths:
x, y = x - 1, y - 1
g[x].append(y)
g[y].append(x)
ans = [0] * n
for x in range(n):
used = {ans[y] for y in g[x]}
for c in range(1, 5):
if c not in used:
ans[x] = c
break
return ans
Complexity
The time complexity is , and the space complexity is , where is the number of gardens and is the number of paths. The space complexity is , where is the number of gardens and is the number of paths.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.