Flower Planting With No Adjacent — LeetCode 1042 Python Solution

MediumDepth-First SearchBreadth-First SearchGraph
Problem
#1042
Reading time
3 min

The problem

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.

Example

Input
n = 3, paths = [[1,2],[2,3],[3,1]]
Output
[1,2,3]
Explanation
Gardens 1 and 2 have different types.

Python solution

Python
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

MeasureComplexity
TimeO(n + m)
SpaceO(n + m), where n is the number of gardens and m is the number of paths auxiliary

Pattern: Breadth-First Search

Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 1042. Flower Planting With No Adjacent is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.

The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1042. Flower Planting With No Adjacent?
LeetCode 1042. Flower Planting With No Adjacent is rated Medium on LeetCode.
What is the time complexity of LeetCode 1042. Flower Planting With No Adjacent?
The Python solution on this page runs in O(n + m).
What is the space complexity of LeetCode 1042. Flower Planting With No Adjacent?
The Python solution on this page uses O(n + m), where n is the number of gardens and m is the number of paths auxiliary space.
What topics does LeetCode 1042. Flower Planting With No Adjacent cover?
LeetCode 1042. Flower Planting With No Adjacent is tagged Depth-First Search, Breadth-First Search and Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview