Google SWE L4 on-site interview DSA

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-12-17Added By Anonymous
Source: Link

Company: Google
Role: L4 (SWE2)
Interview Stage: Onsite
Location: unknown
Year: unknown

Original Post Content:

Got this one in the interview, still not sure how to solve it. Need help from great leetcoders.
Problem:
You are given a tree with n nodes (labeled from 0 to n-1), and each node is colored with one of the letters ‘R’, ‘A’, or ‘W’. A tree is defined by having n-1 edges and no cycles. Additionally, each node has at most three neighbors.

We want to determine if there exists a node that can serve as a root of a binary tree such that the colors of the nodes follow one of the six possible repeating 3-color patterns level by level from that root. The six possible 3-color patterns are:
• RWA
• RAW
• WAR
• WRA
• ARW
• AWR

“Following the pattern” means that if the chosen pattern is p, then every node at depth d from the root (0-based) must have the color p[d % 3]. The graph should form a binary tree starting from the root. If there exists such a root and a pattern, return the index of that root. If multiple such roots exist, returning any one of them is fine. If no solution exists, return None.

Note:
• If the tree has only one node, any pattern starting with that node’s color will work, so that single node can be the root.
• Time complexity should be O(V), O(V^2) is considered brute force. The interviewer hinted that the tc is O(6 * V) -> O(V).

Input Format:
• edges: A list of pairs [u, v] representing the undirected edges of the tree.
• colors: A list of characters (‘R’, ‘A’, ‘W’) of length n, where colors[i] is the color of node i.

Output Format:
• Return the index of a valid root node if it exists.
• If no solution exists, return -1.

Examples:

Example 1:

n = 3
edges = [[0,1],[0,2]]
colors = ['R','W','W']

Possible pattern: RWA
- Depth 0: R
- Depth 1: W
For root=0:
- Node 0 at depth 0 = 'R' matches 'R'
- Nodes 1,2 at depth 1 = 'W','W' match 'W'
Matches pattern RWA starting at root=0.

Output: 0

Example 2:
n = 6
edges = [[0,1],[0,2],[1,3],[1,4],[2,5]]
colors = ['R','A','A','W','W','W']

Pattern RAW:
- Depth 0: R
- Depth 1: A
- Depth 2: W
For root=0 with RAW:
- Node 0='R', depth 0 → R ✓
- Nodes 1,2='A','A', depth 1 → A ✓
- Nodes 3,4,5='W','W','W', depth 2 → W ✓
All match perfectly.

Output: 0

Example 3:
n = 3
edges = [[0,1],[1,2]]
colors = ['R','R','R']

No pattern can fit a tree where all nodes have the same color and we need a 3-color repeating pattern.

Output: -1

My Solution: ***Not validated yet, help needed***
This is the solution I have for now, but I'm not 100% confident.
Thanks for all the ideas. I've got an O(6V) alg as well. This one is inspired by Rishi.
We focus on a single pattern each time and only try to find candidate roots for the graph tree that follows the pattern.
For example, if we are trying to find the root of "RAW", few pattern would be found:
the root's color is "R"
the roots has 1 or 2 neighbor
all the neighbor must be "A"
If the tree follows pattern "RAW", only one candidate root would be found, BFS from that root and validate the whole tree.
We go thru all 6 patterns with the same algorithm, return any valid root.
Python test env and test cases are provided below as well.

from collections import deque


class Solution:
def find_root(self, graph, colors, pat):
n = len(colors)
for node in range(n):
if colors[node] != pat[0] or len(graph[node]) == 3:
continue
if len(graph[node]) == 2 and colors[graph[node][0]] == pat[1] and colors[graph[node][1]] == pat[1]:
return node
elif len(graph[node]) == 1 and colors[graph[node][0]] == pat[1]:
return node
return None

def check_root(self, root, graph, colors, pat): deq = deque([root])
dist = 0
seen = set([root])
while deq:
sz = len(deq)
for _ in range(sz):
cur = deq.popleft()
if colors[cur] != pat[dist % 3]:
return False
for nx in graph[cur]:
if nx in seen:
continue
seen.add(nx)
deq.append(nx)
dist += 1
return True


def solve(self, edges, colors): if not edges:
return 0
n = len(colors)
graph = [[] for _ in range(n)]
for s, e in edges:
graph[s].append(e)
graph[e].append(s)
for p in ("RWA", "RAW", "WAR", "WRA", "ARW", "AWR"): root = self.find_root(graph, colors, p)
# print(root)
if root != None and self.check_root(root, graph, colors, p):
return root
return None
Comments