1120. Flower Planting With No Adjacent
My accepted Python solution to LeetCode problem 1120, Flower Planting With No Adjacent, running in 34ms.
- Difficulty: Medium
- Python
- Runtime 34ms
- Memory 22MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 34ms, memory 22MB, accepted 2026-01-02.
class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
# Build adjacency list
graph = [[] for _ in range(n + 1)]
for x, y in paths:
graph[x].append(y)
graph[y].append(x)
result = [0] * (n + 1)
for garden in range(1, n + 1):
# Find colors used by neighbors
used_colors = set()
for neighbor in graph[garden]:
if result[neighbor] != 0:
used_colors.add(result[neighbor])
# Choose first available color
for color in range(1, 5):
if color not in used_colors:
result[garden] = color
break
return result[1:]