#1042

Flower Planting With No Adjacent

Medium
Depth-First SearchBreadth-First SearchGraph TheoryGraph TraversalGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the fact that each garden has at most 3 neighbors, allowing us to always find an available flower type. We can simply iterate through each garden and assign a flower that is not used by its neighbors.

⚙️

Algorithm

4 steps
  1. 1Step 1: Build an adjacency list to represent the gardens and their connections.
  2. 2Step 2: Initialize an array to store the flower types for each garden.
  3. 3Step 3: For each garden, determine which flower types are already used by its neighbors.
  4. 4Step 4: Assign the first available flower type to the current garden.
solution.py18 lines
1# Full working Python code
2class Solution:
3    def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
4        graph = [[] for _ in range(n)]
5        for x, y in paths:
6            graph[x-1].append(y-1)
7            graph[y-1].append(x-1)
8        answer = [0] * n
9        for i in range(n):
10            used = [False] * 5
11            for neighbor in graph[i]:
12                if answer[neighbor] != 0:
13                    used[answer[neighbor]] = True
14            for flower in range(1, 5):
15                if not used[flower]:
16                    answer[i] = flower
17                    break
18        return answer

Complexity note: The time complexity is O(n) because we only iterate through each garden and its neighbors once, making it efficient. The space complexity is O(n) due to the adjacency list.

  • 1Each garden can have at most 3 neighbors, ensuring at least one flower type is always available.
  • 2Using a greedy approach allows us to efficiently assign flower types without backtracking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.