Practice/Google/Find Root Node in Colored Tree with Pattern Constraints
CodingMust
You are given an undirected connected acyclic graph (a tree) with n nodes labeled from 0 to n-1. Each node is assigned a color represented by a single character. Your task is to find a node that can serve as a valid root such that when the tree is traversed level-by-level starting from that root, all nodes at each depth level match a repeating color pattern.
The pattern is a string that repeats cyclically. For a node at depth d from the root, its color must match pattern[d % len(pattern)]. All nodes at the same depth must satisfy this constraint.
Return the smallest node index that can serve as a valid root. If no such root exists, return -1.
-1 if none existsExample 1:
`
Input: n = 5, edges = [[0,1],[1,2],[1,3],[3,4]], colors = "RBRRB", pattern = "RB"
Output: 0
Explanation:
Tree structure:
0(R)
|
1(B)
/
2(R) 3(R)
|
4(B)
From root 0:
Example 2:
Input: n = 4, edges = [[0,1],[1,2],[2,3]], colors = "RRRR", pattern = "RB" Output: -1 Explanation: All nodes are Red, but the pattern requires alternating Red and Black colors at different levels. No valid root exists.
Example 3:
` Input: n = 7, edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], colors = "RBWRBWW", pattern = "RBW" Output: 0 Explanation: From root 0, levels follow pattern RBW cyclically: