Flower Planting With No Adjacent - 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. All gardens have at most 3 paths coming into or leaving it.

Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.

Return any such choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.

Input & Output

Example 1 — Basic Connected Gardens
$ Input: n = 3, paths = [[1,2],[2,3]]
Output: [1,2,1]
💡 Note: Garden 1 gets flower type 1, garden 2 gets type 2 (can't use 1 due to connection to garden 1), garden 3 gets type 1 (can't use 2 due to connection to garden 2, but can reuse 1)
Example 2 — Triangle Formation
$ Input: n = 4, paths = [[1,2],[1,3],[1,4]]
Output: [1,2,3,4]
💡 Note: Garden 1 is connected to all others, so gardens 2, 3, 4 each need different flower types from garden 1 and can use types 2, 3, 4 respectively
Example 3 — No Connections
$ Input: n = 4, paths = []
Output: [1,1,1,1]
💡 Note: No paths means no restrictions, so all gardens can use the same flower type 1

Constraints

  • 1 ≤ n ≤ 104
  • 0 ≤ paths.length ≤ 2 × 104
  • paths[i].length == 2
  • 1 ≤ xi, yi ≤ n
  • xi ≠ yi
  • Every garden has at most 3 paths coming into or leaving it

Visualization

Tap to expand
Flower Planting With No Adjacent INPUT Graph with n=3 gardens 1 2 3 n = 3 paths = [[1,2],[2,3]] 4 flower types available Max 3 paths per garden ALGORITHM STEPS 1 Build Adjacency List 1: [2], 2: [1,3], 3: [2] 2 Process Garden 1 No neighbors colored Assign flower type 1 3 Process Garden 2 Neighbor 1 has type 1 Assign flower type 2 4 Process Garden 3 Neighbor 2 has type 2 Assign flower type 1 Greedy Selection: Pick first available color not used by neighbors FINAL RESULT Colored Gardens G1 F:1 G2 F:2 G3 F:1 OK OK Output: [1, 2, 1] All adjacent gardens have different flowers Key Insight: With 4 colors and at most 3 neighbors per node, greedy coloring always works! Each garden has at most 3 paths, so at least 1 of 4 flower types is always available. Time: O(n + paths), Space: O(n) - No backtracking needed, simple linear scan suffices. TutorialsPoint - Flower Planting With No Adjacent | Greedy Graph Coloring Approach
Asked in
Google 45 Facebook 32 Amazon 28
28.0K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen