Longest Path With Different Adjacent Characters
Given a tree represented by parent array and a string s where s[i] is the character assigned to node i, return the length of the longest path where adjacent nodes have different characters.

30:00

Longest Path With Different Adjacent Characters
hard
Topics
Companies

Given a tree represented by parent array and a string s where s[i] is the character assigned to node i, return the length of the longest path where adjacent nodes have different characters.

Example 1:
Input: {"parent":[-1,0,0,1,1,2],"s":"abacbe"}
Output: 3
Constraints:
  • n==parent.length==s.lengthn == \text{parent.length} == s.\text{length}

  • 1n1051 \leq n \leq 10^5

  • 0parent[i]n10 \leq \text{parent}[i] \leq n - 1 for all i1i \geq 1.

  • parent[0]==1\text{parent}[0] == -1

  • s consists of lowercase English letters.

Input
arr ={"parent":[-1,0,0,1,1,2],"s":"abacbe"}

Tree with 6 nodes, s="abacbe"

Tree with Character Labels

a0b1a2c3b4e5

Longest Path:

1

Current Node

In Path

Variables
No variables to display
DepthFunction Call
Stack empty
0/1