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
Longest Path With Different Adjacent Characters INPUT Tree Structure (rooted at 0) a 0 b 1 a 2 c 3 b 4 e 5 parent = [-1,0,0,1,1,2] s = "abacbe" Index: 0 1 2 3 4 5 Char: a b a c b e ALGORITHM STEPS (DFS Tree Diameter) 1 Build adjacency list Convert parent array to child relationships 2 DFS from each node Return longest path from node to any descendant 3 Check adjacent chars Only extend path if s[parent] != s[child] 4 Combine two best paths Max path through node = top1 + top2 + 1 DFS at node 0 (char 'a'): Child 1 (b): path=2 [OK] Child 2 (a): path=0 [SKIP] same char as parent! Best paths: top1=2, top2=0 Through node 0: 2+0+1=3 FINAL RESULT Longest Valid Path Highlighted a 0 b 1 a 2 c 3 b 4 e 5 Path: 3 --> 1 --> 0 Characters: c --> b --> a All adjacent chars different! Output: 3 Key Insight: The problem is similar to finding tree diameter. For each node, we track the two longest paths to descendants with different adjacent characters. The longest path through any node is the sum of these two best paths plus 1 (for the node itself). DFS processes children before parents. TutorialsPoint - Longest Path With Different Adjacent Characters | DFS Tree Diameter Approach
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
32.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen