Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Longest Path With Different Adjacent Characters

XPChallenge Points: 30
levelLevel: Hard

You are given a tree of n nodes (no cycles, fully connected).
Each node has an index from 0 to n - 1.
The tree structure is provided using the array parent, where parent[i] is the parent of node i, and node 0 is the root (so parent[0] = -1).

You are also given a string s, where each character s[i] corresponds to the label assigned to node i.

You must find the maximum length of a path in this tree such that for every pair of adjacent nodes in the path, the characters assigned to them are different.

Return the length of this longest valid path.

Example 1:

Input: parent = [-1, 0, 1, 1, 3] s = "abcda"

Output: 4

Explanation:

Tree structure: 0 └─1 ├─2 └─3 └─4 Longest valid path is: 2 -> 1 -> 3 -> 4 Characters: c → b → d → a (all different)

Example 2:

Input: parent = [-1, 0, 1, 1, 2] s = "aaaaa"

Output: 1

Explanation:

Every adjacent pair has the same character. So each valid path length is 1.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result