You are given a tree (a connected, undirected graph with no cycles) rooted at node 0, with n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of length n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.
You are also given a string s of length n, where s[i] is the character assigned to node i.
Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.
Function Signature
def longest_path(parent: list[int], s: str) -> int:
Rules
-
A path is a sequence of distinct nodes in which every consecutive pair is joined by a tree edge. It can start and end at any nodes. It does not have to pass through the root or run only downward.
-
The length of a path is the number of nodes on it. A single node is a valid path of length 1, so the answer is always at least 1.
-
parent[i]
can be larger than
i
. Node numbers say nothing about depth.
Constraints
-
n == len(parent) == len(s)
-
1 <= n <= 10^5
-
0 <= parent[i] <= n - 1
for every
i >= 1
-
parent[0] == -1
-
parent
represents a valid tree.
-
s
consists of lowercase English letters.
Examples
Input: parent = [-1, 0, 0, 1, 1, 2], s = "abacbe"
Output: 3
Node 0 (a) has children 1 (b) and 2 (a), node 1 has children 3 (c) and 4 (b), and node 2 has child 5 (e). The path 3, 1, 0 reads c, b, a and has 3 nodes; it cannot grow, because node 2 shares 'a' with node 0 and node 4 shares 'b' with node 1.
Input: parent = [-1, 0, 0, 0], s = "aabc"
Output: 3
Node 0 (a) has children 1 (a), 2 (b) and 3 (c). The path 2, 0, 3 reads b, a, c, and node 1 cannot join it because it shares 'a' with node 0.
Input: parent = [-1, 4, 1, 4, 0], s = "abdca"
Output: 4
Node 0 (a) has child 4 (a), node 4 has children 1 (b) and 3 (c), and node 1 has child 2 (d). The edge between nodes 0 and 4 joins two 'a' nodes, so the longest path stays below the root: 2, 1, 4, 3 reads d, b, a, c.