Quick Overview

Given a tree in which every vertex has at most three neighbours, choose a root that makes it a valid binary tree, then extend the rule so every level shares one color and level colors follow a fixed cycle of two or three colors. Tests tree rooting, degree reasoning and checking color constraints across all candidate roots efficiently.

Choose a Root That Makes a Tree a Binary Tree with Cyclic Level Colors

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Technical Screen

You are given an undirected graph with `n` vertices labeled `0` to `n - 1`, where `graph[i]` lists the neighbours of vertex `i`. The graph is connected and acyclic, so it is a tree, and every vertex has at most 3 neighbours. Choosing a vertex as the root turns the tree into a rooted tree: every other vertex's parent is its neighbour on the path toward the root, and its remaining neighbours are its children. The root has depth 0, and a child is one level deeper than its parent. The rooted tree is a valid binary tree when every vertex has at most 2 children. The problem comes in three stages, and one function handles all of them through the `colors` and `cycle` arguments: 1. **No colors** (`colors` and `cycle` are empty): find a root that makes the tree a valid binary tree. 2. **Two alternating colors** (`cycle = ["black", "white"]`): every vertex is black or white. The root must also give every level a single color, with colors alternating between consecutive levels, so the levels read black, white, black and so on, or white, black, white and so on. 3. **Three colors in a fixed cycle** (`cycle = ["red", "white", "black"]`): level colors must follow red → white → black → red as depth increases. The root may have any of the three colors. Return the index of a valid root. If several vertices are valid roots, return the smallest index. If none is, return `-1`. ### Function Signature ```python def find_binary_tree_root(graph: list[list[int]], colors: list[str], cycle: list[str]) -> int: ``` ### Rules - Vertex `r` is a valid root when, with the tree rooted at `r`, every vertex has at most 2 children and, if `cycle` is nonempty, every vertex at depth `d` has color `cycle[(s + d) % len(cycle)]`, where `s` is the position of `colors[r]` in `cycle`. - This rule covers every stage: with two colors it forces alternation starting from the root's color, and with three colors it forces the fixed order starting from the root's color. - When `cycle` is empty there is no color rule, and `colors` is empty too. - If more than one vertex is a valid root, return the smallest one. If no vertex is a valid root, return `-1`. ### Constraints - `n == len(graph)` and `1 <= n <= 10^5` - `graph` is a tree: `j` is in `graph[i]` exactly when `i` is in `graph[j]`, there are no self-loops or repeated neighbours, there are exactly `n - 1` edges, and every vertex is reachable from vertex `0`. - `len(graph[i]) <= 3` for every vertex `i`. - `0 <= len(cycle) <= 10`, the names in `cycle` are distinct, and each name is 1 to 10 lowercase English letters. - If `cycle` is empty then `colors` is empty; otherwise `len(colors) == n` and every `colors[i]` appears in `cycle`. - The result is `-1` or a vertex index from `0` to `n - 1`. ### Examples #### Example 1 ```text Input: graph = [[1,2,3],[0],[0],[0]], colors = [], cycle = [] Output: 1 ``` As the root, vertex 0 would have three children. Rooted at vertex 1, vertex 0 is its only child and has children 2 and 3. Vertices 1, 2 and 3 are all valid roots, and 1 is the smallest. #### Example 2 ```text Input: graph = [[1],[0,2,3],[1],[1,4],[3]], colors = ["black","white","black","black","white"], cycle = ["black","white"] Output: 0 ``` Rooted at vertex 0, the levels are vertex 0 (black), vertex 1 (white), vertices 2 and 3 (black) and vertex 4 (white). Vertex 1 has two children and vertex 3 has one. #### Example 3 ```text Input: graph = [[1],[0,2,3],[1],[1,4],[3]], colors = ["red","black","red","white","red"], cycle = ["red","white","black"] Output: 4 ``` Rooted at vertex 4 (red), depth 1 is vertex 3 (white), depth 2 is vertex 1 (black) and depth 3 is vertices 0 and 2 (red). Every other root breaks the order. For example, rooted at vertex 0 (red), depth 1 must be white, but vertex 1 is black.

Overview: Given a tree in which every vertex has at most three neighbours, choose a root that makes it a valid binary tree, then extend the rule so every level shares one color and level colors follow a fixed cycle of two or three colors. Tests tree rooting, degree reasoning and checking color constraints across all candidate roots efficiently.

Read the full Google Software Engineer interview experience this question came from

You are given an undirected tree with `n` vertices labeled `0` to `n - 1`, where `graph[i]` lists the neighbours of vertex `i`. The graph is connected and acyclic, and every vertex has at most 3 neighbours. Choosing a vertex as the root turns the tree into a rooted tree: every other vertex's parent is its neighbour on the path toward the root, and its remaining neighbours are its children. The root has depth 0, and a child is one level deeper than its parent. The rooted tree is a valid binary tree when every vertex has at most 2 children. The problem comes in three stages, and one function handles all of them through the `colors` and `cycle` arguments: 1. **No colors** (`colors` and `cycle` are empty): find a root that makes the tree a valid binary tree. 2. **Two alternating colors** (`cycle = ["black", "white"]`): every vertex is black or white. The root must also give every level a single color, with colors alternating between consecutive levels, so the levels read black, white, black and so on, or white, black, white and so on. 3. **Three colors in a fixed cycle** (`cycle = ["red", "white", "black"]`): level colors must follow red, white, black, red and so on as depth increases. The root may have any of the three colors. The rules below apply to any `cycle` the constraints allow, including a single color or up to 10 names. ### Rules - Vertex `r` is a valid root when, with the tree rooted at `r`, every vertex has at most 2 children and, if `cycle` is nonempty, every vertex at depth `d` has color `cycle[(s + d) % len(cycle)]`, where `s` is the position of `colors[r]` in `cycle`. - With two colors this forces alternation starting from the root's color, and with three colors it forces the fixed order starting from the root's color. - When `cycle` is empty there is no color rule, and `colors` is empty too. - If more than one vertex is a valid root, return the smallest one. If no vertex is a valid root, return `-1`. ### Example 1 ```text Input: graph = [[1,2,3],[0],[0],[0]], colors = [], cycle = [] Output: 1 ``` As the root, vertex 0 would have three children. Rooted at vertex 1, vertex 0 is its only child and has children 2 and 3. Vertices 1, 2 and 3 are all valid roots, and 1 is the smallest. ### Example 2 ```text Input: graph = [[1],[0,2,3],[1],[1,4],[3]], colors = ["red","black","red","white","red"], cycle = ["red","white","black"] Output: 4 ``` Rooted at vertex 4 (red), depth 1 is vertex 3 (white), depth 2 is vertex 1 (black) and depth 3 is vertices 0 and 2 (red). Every other root breaks the order. For example, rooted at vertex 0 (red), depth 1 must be white, but vertex 1 is black. ### Constraints - `n == len(graph)` and `1 <= n <= 10^5` - `graph` is a tree: `j` is in `graph[i]` exactly when `i` is in `graph[j]`, there are no self-loops or repeated neighbours, there are exactly `n - 1` edges, and every vertex is reachable from vertex `0`. - `len(graph[i]) <= 3` for every vertex `i`. - `0 <= len(cycle) <= 10`, the names in `cycle` are distinct, and each name is 1 to 10 lowercase English letters. - If `cycle` is empty then `colors` is empty; otherwise `len(colors) == n` and every `colors[i]` appears in `cycle`. - The result is `-1` or a vertex index from `0` to `n - 1`. Every value fits in a 32-bit signed integer. In Java `graph` arrives as `int[][]` and the names as `String[]`; in C++ they arrive as `std::vector<std::vector<int>>` and `std::vector<std::string>`.

Constraints

  • `n == len(graph)` and `1 <= n <= 10^5`
  • `graph` is a tree: `j` is in `graph[i]` exactly when `i` is in `graph[j]`, there are no self-loops or repeated neighbours, there are exactly `n - 1` edges, and every vertex is reachable from vertex `0`.
  • `len(graph[i]) <= 3` for every vertex `i`.
  • `0 <= len(cycle) <= 10`, the names in `cycle` are distinct, and each name is 1 to 10 lowercase English letters.
  • If `cycle` is empty then `colors` is empty; otherwise `len(colors) == n` and every `colors[i]` appears in `cycle`.
  • The result is `-1` or a vertex index from `0` to `n - 1`.

Examples

Input: ([[1, 2, 3], [0], [0], [0]], [], [])

Expected Output: 1

Explanation: Source Example 1: centre 0 has degree 3, so it would have three children; leaves 1, 2 and 3 are valid and 1 is the smallest.

Input: ([[1], [0, 2, 3], [1], [1, 4], [3]], ['black', 'white', 'black', 'black', 'white'], ['black', 'white'])

Expected Output: 0

Explanation: Source Example 2: every edge joins black and white and vertex 0 is a leaf, so 0 is valid.

Hints

  1. Once a root is fixed, how many children does the root have, and how many does every other vertex have? Use the limit of 3 neighbours per vertex.
  2. The color rule is stated by depth, but it can be checked edge by edge: when `u` is the parent of `v`, what must hold between their positions in `cycle`?
  3. With an empty cycle or a cycle of two colors, several roots can be valid at once, so the answer is the smallest index among all valid roots.

Smallest Valid Root for a Level-Colored Binary Tree

easyGoogleSoftware Engineer

You are given an undirected tree with n vertices labeled 0 to n - 1, where graph[i] lists the neighbours of vertex i. The graph is connected and acyclic, and every vertex has at most 3 neighbours.

Choosing a vertex as the root turns the tree into a rooted tree: every other vertex's parent is its neighbour on the path toward the root, and its remaining neighbours are its children. The root has depth 0, and a child is one level deeper than its parent. The rooted tree is a valid binary tree when every vertex has at most 2 children.

The problem comes in three stages, and one function handles all of them through the colors and cycle arguments:

  1. No colors (colors and cycle are empty): find a root that makes the tree a valid binary tree.
  2. Two alternating colors (cycle = ["black", "white"]): every vertex is black or white. The root must also give every level a single color, with colors alternating between consecutive levels, so the levels read black, white, black and so on, or white, black, white and so on.
  3. Three colors in a fixed cycle (cycle = ["red", "white", "black"]): level colors must follow red, white, black, red and so on as depth increases. The root may have any of the three colors.

The rules below apply to any cycle the constraints allow, including a single color or up to 10 names.

Rules

  • Vertex r is a valid root when, with the tree rooted at r, every vertex has at most 2 children and, if cycle is nonempty, every vertex at depth d has color cycle[(s + d) % len(cycle)], where s is the position of colors[r] in cycle.
  • With two colors this forces alternation starting from the root's color, and with three colors it forces the fixed order starting from the root's color.
  • When cycle is empty there is no color rule, and colors is empty too.
  • If more than one vertex is a valid root, return the smallest one. If no vertex is a valid root, return -1.

Example 1

Input:  graph = [[1,2,3],[0],[0],[0]], colors = [], cycle = []
Output: 1

As the root, vertex 0 would have three children. Rooted at vertex 1, vertex 0 is its only child and has children 2 and 3. Vertices 1, 2 and 3 are all valid roots, and 1 is the smallest.

Example 2

Input:  graph = [[1],[0,2,3],[1],[1,4],[3]], colors = ["red","black","red","white","red"], cycle = ["red","white","black"]
Output: 4

Rooted at vertex 4 (red), depth 1 is vertex 3 (white), depth 2 is vertex 1 (black) and depth 3 is vertices 0 and 2 (red). Every other root breaks the order. For example, rooted at vertex 0 (red), depth 1 must be white, but vertex 1 is black.

Constraints

  • n == len(graph) and 1 <= n <= 10^5
  • graph is a tree: j is in graph[i] exactly when i is in graph[j], there are no self-loops or repeated neighbours, there are exactly n - 1 edges, and every vertex is reachable from vertex 0.
  • len(graph[i]) <= 3 for every vertex i.
  • 0 <= len(cycle) <= 10, the names in cycle are distinct, and each name is 1 to 10 lowercase English letters.
  • If cycle is empty then colors is empty; otherwise len(colors) == n and every colors[i] appears in cycle.
  • The result is -1 or a vertex index from 0 to n - 1.

Every value fits in a 32-bit signed integer. In Java graph arrives as int[][] and the names as String[]; in C++ they arrive as std::vector<std::vector<int>> and std::vector<std::string>.

Examples

Example 1
Input
([[1, 2, 3], [0], [0], [0]], [], [])
Output
1
Notes
Source Example 1: centre 0 has degree 3, so it would have three children; leaves 1, 2 and 3 are valid and 1 is the smallest.
Example 2
Input
([[1], [0, 2, 3], [1], [1, 4], [3]], ['black', 'white', 'black', 'black', 'white'], ['black', 'white'])
Output
0
Notes
Source Example 2: every edge joins black and white and vertex 0 is a leaf, so 0 is valid.

Constraints

  • •`n == len(graph)` and `1 <= n <= 10^5`
  • •`graph` is a tree: `j` is in `graph[i]` exactly when `i` is in `graph[j]`, there are no self-loops or repeated neighbours, there are exactly `n - 1` edges, and every vertex is reachable from vertex `0`.
  • •`len(graph[i]) <= 3` for every vertex `i`.
  • •`0 <= len(cycle) <= 10`, the names in `cycle` are distinct, and each name is 1 to 10 lowercase English letters.
  • •If `cycle` is empty then `colors` is empty; otherwise `len(colors) == n` and every `colors[i]` appears in `cycle`.
  • •The result is `-1` or a vertex index from `0` to `n - 1`.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def find_binary_tree_root(graph: list[list[int]], colors: list[str], cycle: list[str]) -> int:
Sample call
find_binary_tree_root([[1, 2, 3], [0], [0], [0]], [], [])
Language
Case 1
Input
([[1, 2, 3], [0], [0], [0]], [], [])
Expected
1
Case 2
Input
([[1], [0, 2, 3], [1], [1, 4], [3]], ['black', 'white', 'black', 'black', 'white'], ['black', 'white'])
Expected
0

Browse More Questions

Show the approach

Approach

Rooted at r, the root has len(graph[r]) children and every other vertex v has len(graph[v]) - 1 children. No vertex has more than 3 neighbours, so the binary tree condition holds exactly when len(graph[r]) <= 2.

For the color rule let m = len(cycle) and let pos[v] be the position of colors[v] in cycle. The depth rule holds for every vertex exactly when every parent u and child v satisfy pos[v] == (pos[u] + 1) % m: the root meets the rule through the choice of s, and each step one level down adds 1 to the required position. So each edge, read away from the root, either keeps the rule or breaks it.

Let bad[r] be the number of edges that break the rule when the tree is rooted at r. An iterative BFS from vertex 0 gives every parent and a visiting order, and bad[0] counts the breaking parent-to-child edges. Moving the root from u to its child v reverses only the edge between them, so bad[v] = bad[u] - breaks(u, v) + breaks(v, u). Filling bad in BFS order takes O(n). A vertex r is valid exactly when bad[r] == 0 and len(graph[r]) <= 2, and scanning r upward from 0 returns the smallest valid root, or -1 when there is none.

Edge cases: with an empty cycle no edge breaks the rule, so only degrees matter. With one color (pos[u] + 1) % 1 == 0 holds on every edge. With two colors both directions of an edge give the same result, so several roots can be valid; with three or more colors at most one direction of each edge fits, and an edge whose colors are not next to each other in the cycle fits in neither direction, which makes the answer -1. A single vertex is always valid. The BFS uses no recursion, so a path of 10^5 vertices is safe.

Time complexity:
O(n)
Space complexity:
O(n)