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: Ensure Adjacent Gardens Have Different FlowersINPUT123paths = [[1,2],[2,3]]OUTPUT121result = [1,2,1]✓ Adjacent gardens have different flower types
Understanding the Visualization
1
Input
Gardens connected by bidirectional paths
2
Process
Assign flowers ensuring adjacent gardens differ
3
Output
Valid flower assignment array
Key Takeaway
🎯 Key Insight: With 4 flower types and max 3 neighbors per garden, there's always a valid flower choice available
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