Hard · Trees

Longest Path With Different Adjacent Characters

Given a tree of n nodes rooted at node 0 (parent[i] is the parent of node i, and parent[0] = −1) and a string s of n lowercase English letters where s[i] labels node i, return the number of nodes on the longest path in which no two adjacent nodes have the same letter.

Examples

Example 1

parent=[-1,0,0,1,1,2], s="abacbe" → 3

Output: 3 nodes

Example 2

parent=[-1,0,1,0,3], s="abcbd" → 5

Output: 5 nodes

Rebuild it in the studio

Open every published interview problem, solution, scene, and memory room free, with no account.

More Trees problems