MediumDepth-First SearchBreadth-First SearchGraphGreedy

Flower Planting With No Adjacent

LeetCode
1 approach, code in all languages

You have n gardens labeled from 1 to n, and a list of bidirectional paths where each path [x, y] connects garden x and garden y. Every garden is directly connected to at most three other gardens.

There are four kinds of flowers, labeled 1, 2, 3, and 4. You must plant exactly one kind of flower in each garden so that any two gardens joined by a path use different kinds of flowers.

Return any valid assignment as an array of length n, where the i-th value is the flower type planted in garden i + 1. The problem guarantees that at least one valid answer exists.

Example 1

Input: n = 3, paths = [[1,2],[2,3],[3,1]]

Output: [1,2,3]

The three gardens form a triangle, so each must differ from the other two. Assigning 1, 2, and 3 satisfies every path; any permutation of three distinct types also works.

Example 2

Input: n = 4, paths = [[1,2],[3,4]]

Output: [1,2,1,2]

Gardens 1 and 2 must differ and gardens 3 and 4 must differ, but the two pairs are independent, so the pattern 1, 2, 1, 2 is valid.

Constraints

  • 1 <= n <= 10^4
  • 0 <= paths.length <= 2 * 10^4
  • paths[i].length == 2
  • 1 <= x, y <= n
  • x != y
  • Every garden has at most 3 paths connected to it
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now