Talentd
FleetCode
Make and follow sheets.Sign in

Find Root of a Colored Tree solution and explanation

Medium4 min read41.9% acceptanceUpdated 19 Oct 2026
Leetcode Weekly Contest 524 | Q3 - Find Root of a Colored Tree | 4085 | TREEKumar K [Amazon] · 37:23 · 2K viewsWatch on YouTube
6 more videos on this problem
  1. Leetcode Weekly Contest 524 | Q3 - Find Root of a Colored Tree | 4085 | TREEKumar K [Amazon] · 37:23 · 2K views
  2. Leetcode 4085 | Find Root of a Colored Tree | Leetcode weekly contest 524CodeWithMeGuys · 25:57 · 426 views
  3. Problem Of The Month! | Solution to Leetcode Weekly Contest 524 Q3 (Find Root of a Colored Tree)Jim_X · 11:09 · 398 views
  4. Find Root of a Colored Tree | Binary Tree | Use degress of a node | Leetcode 4085Manjeet Dhayal · 12:38 · 213 views
  5. 4085. Find Root of a Colored Tree | LeetCode Weekly Contest 524 | O(N) Optimal ApproachRealGuideBhai · 17:10 · 164 views
  6. Find Root of a Colored Tree | Leetcode 4085 | Weekly Contest 524 | Dry RunVijay Algorithms · 26:52 · 24 views
  7. LeetCode 4085 Find Root of a Colored Tree — let the colors orient the treePrateek Goel · 13:18 · 16 views

The problem

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.

Approach overview

Problem Overview: You get a rooted tree with n nodes, each labeled with a unique id and a color. The root is the one node that is never listed as a child of another node. Return that node.

Approach 1: Brute Force Child Scan (O(n²) time, O(1) space)

For each candidate node, scan the entire parent-child edge list and check whether the candidate appears as a child anywhere. If it never does, it is the root. The check per node is a linear scan, so the total work is quadratic. This approach needs no extra memory and is useful for confirming the definition before optimizing. Use it only to validate your understanding of the input format.

Approach 2: Hash Set of Children (O(n) time, O(n) space)

Iterate through all edges once and insert every child id into a set. Then iterate over the node ids and return the first one that is not in the set. Each set insertion and hash lookup is O(1) on average, so the total time is linear. The cost is an extra set holding up to n - 1 ids. This is the cleanest approach to write under time pressure and easy to explain in an interview.

Approach 3: Sum Difference (O(n) time, O(1) space)

Compute the sum of all node ids from 1 to n with the formula n(n+1)/2. Then subtract the id of every child as you read the edges. Every non-root node is subtracted exactly once, so the remaining value is the root id. This uses a single integer accumulator and one pass over the edges. Prefer it when memory is constrained or when the interviewer asks for constant extra space.

Recommended for interviews: Start by describing the brute force scan so the interviewer sees you understand the definition of a root. Then move to the hash set approach to reach linear time. Finish with the sum difference trick to show you can reduce space to O(1). The brute force shows understanding, the hash set shows competence, and the sum trick shows you can optimize beyond the obvious. For more practice, see tree problems, hash table problems, and math problems on FleetCode.

The written solution for this problem is still being prepared. Try it yourself in the meantime.

Try solving it yourself

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force Child ScanO(n²)O(1)Validating the input definition only
Hash Set of ChildrenO(n)O(n)General case and interview default
Sum DifferenceO(n)O(1)Memory constrained or when ids are consecutive integers

Frequently asked questions

Find Root of a Colored Tree Python solution

In Python, create a set of all child ids while iterating over the edges, then return the node id not present in that set. Use a running sum of ids minus the child ids for an O(1) space version. Both run in O(n) time.

Is Find Root of a Colored Tree easy or hard?

This problem is rated Medium with a 41.9% acceptance rate. The core idea is simple once you see that the root never appears as a child, but many candidates struggle to reach the O(1) space solution without a hint.

How to solve Find Root of a Colored Tree in O(n)?

Read every edge and mark each child node. The root is the only node that is never marked. Use a hash set for clarity, or subtract each child id from the sum of all ids 1 to n to leave the root id with O(1) extra space.

What is the best approach for Find Root of a Colored Tree?

The best approach is a single pass over the edges that tracks which nodes appear as children. The sum difference method runs in O(n) time with O(1) extra space and is the most memory-efficient option. The hash set method is equally fast and easier to explain.

What data structure is used in Find Root of a Colored Tree?

The hash set approach uses a set to store child node ids for O(1) average lookup. The sum difference approach uses no data structure beyond a single integer accumulator. Both rely on the fact that the root is the only node with no parent.

What is the time complexity of Find Root of a Colored Tree?

The optimal solution runs in O(n) time, where n is the number of nodes, because it reads each edge once. The naive approach that scans the edge list for every candidate takes O(n²) time.

Is Find Root of a Colored Tree asked at Google, Amazon, or Meta?

This problem is not tagged with specific companies on FleetCode, so there is no confirmed company frequency data. The underlying pattern of identifying a root through in-degree or sum tricks appears frequently in tree interview questions across large tech companies.

Comments

Now write it yourselfClose this page and solve Find Root of a Colored Tree in the editor, without looking.
Practise Find Root of a Colored Tree