Leetcode 1042: Flower Planting With No Adjacent

grid47
grid47
Exploring patterns and algorithms
Jul 25, 2024 6 min read

You are given n gardens labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi and garden yi. Each garden needs to be assigned one of 4 types of flowers. You need to ensure that for any two gardens connected by a path, they have different types of flowers. Your task is to return any valid flower assignment for all gardens such that no two adjacent gardens share the same flower type.
Problem
Approach
Steps
Complexity
Input: You are given an integer n, the number of gardens, and a list of pairs paths, where each pair [xi, yi] represents a bidirectional path between garden xi and garden yi.
Example: Input: n = 5, paths = [[1,2], [2,3], [3,4], [4,5]]
Constraints:
• 1 <= n <= 10^4
• 0 <= paths.length <= 2 * 10^4
• paths[i].length == 2
• 1 <= xi, yi <= n
• xi != yi
• Each garden has at most 3 paths coming into or leaving it.
Output: Return an array where the i-th element represents the type of flower planted in the i-th garden. The flower types are denoted by integers 1, 2, 3, or 4.
Example: Output: [1, 2, 3, 4, 1]
Constraints:
• There is guaranteed to be at least one valid answer.
Goal: The goal is to assign flower types to gardens such that no two connected gardens have the same flower type.
Steps:
• 1. Represent the gardens and paths as a graph.
• 2. Use a greedy approach to assign flower types to gardens, making sure adjacent gardens get different flower types.
Goal: The problem has the following constraints:
Steps:
• 1 <= n <= 10^4
• 0 <= paths.length <= 2 * 10^4
• 1 <= xi, yi <= n
• xi != yi
• Every garden has at most 3 paths coming into or leaving it.
Assumptions:
• It is guaranteed that there is always a valid solution.
Input: Input: n = 5, paths = [[1,2], [2,3], [3,4], [4,5]]
Explanation: In this case, we can assign flowers such that adjacent gardens have different types. One valid solution is to assign flowers [1, 2, 1, 2, 1] to gardens [1, 2, 3, 4, 5].

Input: Input: n = 6, paths = [[1,2], [1,3], [2,4], [3,5], [4,6]]
Explanation: Here, we can assign flowers such that adjacent gardens do not share the same flower type. One valid solution is [1, 2, 3, 4, 3, 2].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus