Longest Path With Different Adjacent Characters - Problem

You are given a tree (a connected, undirected graph with no cycles) rooted at node 0, consisting of n nodes numbered from 0 to n - 1. The tree structure 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.

Additionally, you have a string s of length n, where s[i] represents the character assigned to node i.

Your goal: Find the longest path in the tree such that no two adjacent nodes on the path have the same character. The path can start and end at any nodes in the tree.

Note: A path is a sequence of nodes where each adjacent pair is connected by an edge. The length of a path is the number of nodes in it.

Input & Output

example_1.py โ€” Basic Tree
$ Input: parent = [-1,0,0,1,1,2], s = "abacbe"
โ€บ Output: 3
๐Ÿ’ก Note: The longest valid path is 2โ†’0โ†’3 with characters "aca". Nodes 2 and 0 have different characters ('a' and 'b'), and nodes 0 and 3 have different characters ('b' and 'c').
example_2.py โ€” All Same Characters
$ Input: parent = [-1,0,0,0], s = "aaaa"
โ€บ Output: 1
๐Ÿ’ก Note: All nodes have the same character 'a', so no two adjacent nodes can have different characters. The longest valid path contains only one node.
example_3.py โ€” Linear Tree
$ Input: parent = [-1,0,1,2], s = "abcd"
โ€บ Output: 4
๐Ÿ’ก Note: This forms a linear tree 0โ†’1โ†’2โ†’3 with characters "abcd". All adjacent nodes have different characters, so the entire path is valid with length 4.

Constraints

  • n == parent.length == s.length
  • 1 โ‰ค n โ‰ค 105
  • 0 โ‰ค parent[i] โ‰ค n - 1 for all i โ‰ฅ 1
  • parent[0] == -1
  • parent represents a valid tree
  • s consists of only lowercase English letters

Visualization

Tap to expand
ABCDEFLongest Path: Fโ†’Dโ†’Bโ†’ELength: 4 nodesAlgorithm Steps:1. DFS from root (A)2. Process children first3. Combine two longest paths4. Update global maximum
Understanding the Visualization
1
Identify Tree Structure
Convert the parent array into a tree with proper parent-child relationships
2
DFS Traversal
Start from root and visit children first (post-order traversal)
3
Combine Child Paths
At each node, find the two longest valid paths from children with different characters
4
Update Maximum
The longest path through current node is the sum of the two longest child paths plus 1
Key Takeaway
๐ŸŽฏ Key Insight: The longest path in a tree can be found by considering each node as a potential 'bridge' connecting two longest downward paths, using DFS to avoid redundant computations.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 25
52.0K Views
Medium-High Frequency
~25 min Avg. Time
1.4K 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