Skip to content

4085. Find Root of a Colored Tree

SourceWeekly Contest 524 Q3DifficultyMediumRating1878

Description

You are given an undirected tree of n nodes labeled from 0 to n - 1, represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an undirected edge between nodes ui and vi.

You are also given a string colors of length n, where colors[i] is one of 'R', 'B', or 'W', and denotes the color of node i.

A node chosen as root must satisfy both of the following conditions once the tree is oriented away from it:

  1. Binary-tree property: Every node has at most two children.
  2. Layered color pattern: All nodes at the same depth have the same color. Starting at depth 0, these colors follow one of the three repeating sequences:
    • R → B → W → R → B → W → ...
    • B → W → R → B → W → R → ...
    • W → R → B → W → R → B → ...

Return the index of any root that satisfies both conditions, or -1 if no such root exists.

A tree is a connected undirected graph with no cycles.

The depth of a node is the number of edges on the path from the root to that node. The root has depth 0. A child of a node is an adjacent node whose depth is one greater.

The degree of a node is the number of edges incident to it.

 

Example 1:

Input: edges = [[3,1],[3,2],[1,4],[2,0]], colors = "BRRWB"

Output: 3

Explanation:

Rooting at node 3 gives each node at most two children and every edge advances to the next color in the cycle (W → R → B), so return 3.

Example 2:

Input: edges = [[0,1],[1,2],[2,3]], colors = "RBRB"

Output: -1

Explanation:

No root satisfies the required color step on every edge, so return -1.

 

Constraints:

  • 2 <= n <= 105
  • edges.length == n - 1
  • edges[i] = [ui, vi]
  • 0 <= ui, vi < n
  • colors.length == n
  • colors[i] is one of 'R', 'B', 'W'.
  • The input graph is a tree and every node has degree at most three.

Solutions

Solution 1: Orient Edges by Color

Thinking

Trying every node as the root, then checking child counts and the color of each depth, walks the whole tree once per trial. With up to \(10^5\) nodes, repeating that walk \(n\) times takes \(O(n^2)\) time.

The repeated work is the parent-child direction of each edge. The three sequences are the same cycle \(W \to R \to B \to W\), started at different colors. Number \(W,R,B\) as \(0,1,2\). Each extra level of depth adds \(1\) to the color index, modulo \(3\). The two colors decide whether the edge is legal and which endpoint is the parent.

An adjacency list and a count of neighbor colors separate the parent side from the child side. A neighbor of color \((c + 2) \bmod 3\) is the only possible parent, and there can be at most one. A neighbor of the same color is off the cycle. The node with no parent neighbor and degree less than \(3\) has only children, at most two of them, and that node is the root.

Number \(W\), \(R\), and \(B\) as \(0\), \(1\), and \(2\) so that the cycle \(W \to R \to B \to W\) is adding \(1\) modulo \(3\), and build an undirected adjacency list from \(\textit{edges}\). For a node \(u\) with color index \(c\), count the neighbors of each color.

Return \(-1\) if the degree is greater than \(3\), if any neighbor has the same color, or if more than one neighbor has color \((c + 2) \bmod 3\). The root has no parent and at most two children, so its degree is at most \(2\). Every other node has one more parent, so its degree is at most \(3\). Equal colors cannot occupy adjacent depths. Color \((c + 2) \bmod 3\) is one step earlier in the cycle, so it can only be the parent, and a node has only one parent.

When the degree is less than \(3\) and no neighbor has color \((c + 2) \bmod 3\), every neighbor of \(u\) is a child and there are at most two of them, so record \(u\). Each edge whose colors are one step apart increments the parent count of exactly one endpoint, and a tree has \(n - 1\) edges. If every parent count is at most \(1\), exactly one node has count \(0\). If that node has degree \(3\), all three neighbors are children, so it cannot be the root and the answer stays \(-1\).

The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def findColoredRoot(self, edges: list[list[int]], colors: str) -> int:
        d = {"W": 0, "R": 1, "B": 2}
        n = len(colors)
        g = [[] for _ in range(n)]
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        ans = -1
        for u, vs in enumerate(g):
            if len(vs) > 3:
                return -1
            cnt = [0] * 3
            for v in vs:
                cnt[d[colors[v]]] += 1
            c = d[colors[u]]
            if cnt[c] > 0 or cnt[(c + 2) % 3] > 1:
                return -1
            if len(vs) < 3 and cnt[(c + 2) % 3] == 0:
                ans = u
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
    public int findColoredRoot(int[][] edges, String colors) {
        int n = colors.length();
        int[] d = new int[128];
        d['W'] = 0;
        d['R'] = 1;
        d['B'] = 2;
        List<Integer>[] g = new List[n];
        Arrays.setAll(g, k -> new ArrayList<>());
        for (int[] e : edges) {
            int u = e[0], v = e[1];
            g[u].add(v);
            g[v].add(u);
        }
        int ans = -1;
        for (int u = 0; u < n; ++u) {
            List<Integer> vs = g[u];
            if (vs.size() > 3) {
                return -1;
            }
            int[] cnt = new int[3];
            for (int v : vs) {
                ++cnt[d[colors.charAt(v)]];
            }
            int c = d[colors.charAt(u)];
            if (cnt[c] > 0 || cnt[(c + 2) % 3] > 1) {
                return -1;
            }
            if (vs.size() < 3 && cnt[(c + 2) % 3] == 0) {
                ans = u;
            }
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
    int findColoredRoot(vector<vector<int>>& edges, string colors) {
        int d[128]{};
        d['W'] = 0;
        d['R'] = 1;
        d['B'] = 2;
        int n = colors.size();
        vector<vector<int>> g(n);
        for (auto& e : edges) {
            int u = e[0], v = e[1];
            g[u].push_back(v);
            g[v].push_back(u);
        }
        int ans = -1;
        for (int u = 0; u < n; ++u) {
            auto& vs = g[u];
            if (vs.size() > 3) {
                return -1;
            }
            int cnt[3]{};
            for (int v : vs) {
                ++cnt[d[colors[v]]];
            }
            int c = d[colors[u]];
            if (cnt[c] > 0 || cnt[(c + 2) % 3] > 1) {
                return -1;
            }
            if (vs.size() < 3 && cnt[(c + 2) % 3] == 0) {
                ans = u;
            }
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func findColoredRoot(edges [][]int, colors string) int {
    d := [128]int{'W': 0, 'R': 1, 'B': 2}
    n := len(colors)
    g := make([][]int, n)
    for _, e := range edges {
        u, v := e[0], e[1]
        g[u] = append(g[u], v)
        g[v] = append(g[v], u)
    }
    ans := -1
    for u, vs := range g {
        if len(vs) > 3 {
            return -1
        }
        cnt := [3]int{}
        for _, v := range vs {
            cnt[d[colors[v]]]++
        }
        c := d[colors[u]]
        if cnt[c] > 0 || cnt[(c+2)%3] > 1 {
            return -1
        }
        if len(vs) < 3 && cnt[(c+2)%3] == 0 {
            ans = u
        }
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function findColoredRoot(edges: number[][], colors: string): number {
    const d: Record<string, number> = { W: 0, R: 1, B: 2 };
    const n = colors.length;
    const g: number[][] = Array.from({ length: n }, () => []);
    for (const [u, v] of edges) {
        g[u].push(v);
        g[v].push(u);
    }
    let ans = -1;
    for (let u = 0; u < n; ++u) {
        const vs = g[u];
        if (vs.length > 3) {
            return -1;
        }
        const cnt = [0, 0, 0];
        for (const v of vs) {
            ++cnt[d[colors[v]]];
        }
        const c = d[colors[u]];
        if (cnt[c] > 0 || cnt[(c + 2) % 3] > 1) {
            return -1;
        }
        if (vs.length < 3 && cnt[(c + 2) % 3] === 0) {
            ans = u;
        }
    }
    return ans;
}

Comments