Longest Path With Different Adjacent Characters - Problem
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size 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.
Input & Output
Example 1 — Basic Tree
$
Input:
parent = [-1,0,0,1,1,2], s = "abacbe"
›
Output:
3
💡 Note:
The longest valid path is 3→1→0→2 or 4→1→0→2 with length 3, where no adjacent nodes have the same character.
Example 2 — All Same Characters
$
Input:
parent = [-1,0,1], s = "aaa"
›
Output:
1
💡 Note:
Since all nodes have the same character 'a', no path with different adjacent characters can have length > 1.
Example 3 — Linear Tree
$
Input:
parent = [-1,0,1,2], s = "abab"
›
Output:
4
💡 Note:
The path 0→1→2→3 has alternating characters a,b,a,b so the entire tree forms one valid path of length 4.
Constraints
- n == parent.length == s.length
- 1 ≤ n ≤ 105
- parent[0] == -1
- 0 ≤ parent[i] ≤ n - 1 for i ≥ 1
- parent represents a valid tree
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Tree with parent array [-1,0,0,1,1,2] and characters 'abacbe'
2
Find Valid Paths
Identify paths where adjacent nodes have different characters
3
Maximum Length
Return length of longest valid path found
Key Takeaway
🎯 Key Insight: Use DFS to combine the longest valid paths from each node's children, similar to finding tree diameter
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code