Longest Path With Different Adjacent Characters (LeetCode 2246): Solution and Explanation
A tree rooted at node 0 is given as a parent array, and each node carries a character. Find the longest path, counted in nodes, in which no two neighboring nodes on the path share the same character.
Watch it run step by step
Try your own input and write the code →Intuition
A path in a tree has a single highest node, its top. From that top, the path goes down into at most two different child subtrees. So if we know, for every node, the longest downward chain that starts there and respects the character rule, the longest path through a node is that node plus its two longest valid downward chains from different children. The answer is the best of those values over all nodes.
This is the same structure as the diameter of a binary tree, with two twists. First, a node can have any number of children, so instead of combining left and right we scan all children and keep the top two chain lengths. Second, a child's chain can only be attached when the child's character differs from the node's character. A child with the same character still matters, because its own subtree may contain the best path, but its chain cannot extend through the parent.
A brute force would start a search from every node and explore all paths, which is O(n²). The post-order DFS does everything in one pass. Each call returns the longest valid chain starting at its node and going down, and along the way updates a global best with max1 + max2 + 1, the path that bends at this node. Leaves return 1, and a node whose children all share its character also returns 1, since the chain is just the node itself.
Approach: Post-order DFS with top two chains
- Build a
childrenadjacency list from the parent array, skipping the root at index 0. - Set
self.result = 1, since any single node is a valid path. - Define
dfs(node), which recurses into every child first and gets each child's longest downward chain. - For each child whose character differs from
s[node], update the two largest chain lengthsmax1andmax2. - Update
self.resultwithmax1 + max2 + 1, the best path that bends at this node. - Return
max1 + 1as the longest chain that starts at this node, then calldfs(0)and returnself.result.
Step-by-step example
parent = [-1, 0, 0, 1, 1, 2], s = "abacbe"
- The tree: node 0 ('a') has children 1 ('b') and 2 ('a'). Node 1 has children 3 ('c') and 4 ('b'). Node 2 has child 5 ('e').
- Leaves 3, 4 and 5 each return 1.
- Node 1 ('b'): child 3 ('c') differs, so
max1 = 1. Child 4 ('b') matches and is skipped. The path through node 1 has 1 + 0 + 1 = 2 nodes, soresult = 2. Return 2. - Node 2 ('a'): child 5 ('e') differs, so
max1 = 1. The path is 2 nodes. Return 2. - Node 0 ('a'): child 1 ('b') differs with chain 2, so
max1 = 2. Child 2 ('a') matches and is skipped. The path through 0 has 2 + 0 + 1 = 3 nodes. - The answer is 3, the path 3 to 1 to 0, with characters c, b, a.
Code: Python, Java, C++
1class Solution:
2 def longestPath(self, parent: List[int], s: str) -> int:
3 from collections import defaultdict
4 n = len(parent)
5 children = defaultdict(list)
6 for i in range(1, n):
7 children[parent[i]].append(i)
8
9 self.result = 1
10
11 def dfs(node):
12 # Returns longest path starting from this node going down
13 max1 = max2 = 0 # Two longest paths from children
14
15 for child in children[node]:
16 childLen = dfs(child)
17 if s[child] != s[node]:
18 if childLen > max1:
19 max2 = max1
20 max1 = childLen
21 elif childLen > max2:
22 max2 = childLen
23
24 # Update result: path through this node
25 self.result = max(self.result, max1 + max2 + 1)
26 return max1 + 1
27
28 dfs(0)
29 return self.result1class Solution {
2 int result = 1;
3 List<List<Integer>> children;
4 String s;
5
6 public int longestPath(int[] parent, String s) {
7 int n = parent.length;
8 this.s = s;
9 children = new ArrayList<>();
10 for (int i = 0; i < n; i++) children.add(new ArrayList<>());
11 for (int i = 1; i < n; i++) children.get(parent[i]).add(i);
12
13 dfs(0);
14 return result;
15 }
16
17 private int dfs(int node) {
18 int max1 = 0, max2 = 0;
19
20 for (int child : children.get(node)) {
21 int childLen = dfs(child);
22 if (s.charAt(child) != s.charAt(node)) {
23 if (childLen > max1) {
24 max2 = max1;
25 max1 = childLen;
26 } else if (childLen > max2) {
27 max2 = childLen;
28 }
29 }
30 }
31
32 result = Math.max(result, max1 + max2 + 1);
33 return max1 + 1;
34 }
35}1class Solution {
2public:
3 int result = 1;
4
5 int longestPath(vector<int>& parent, string s) {
6 int n = parent.size();
7 vector<vector<int>> children(n);
8 for (int i = 1; i < n; i++) {
9 children[parent[i]].push_back(i);
10 }
11
12 function<int(int)> dfs = [&](int node) -> int {
13 int max1 = 0, max2 = 0;
14
15 for (int child : children[node]) {
16 int childLen = dfs(child);
17 if (s[child] != s[node]) {
18 if (childLen > max1) {
19 max2 = max1;
20 max1 = childLen;
21 } else if (childLen > max2) {
22 max2 = childLen;
23 }
24 }
25 }
26
27 result = max(result, max1 + max2 + 1);
28 return max1 + 1;
29 };
30
31 dfs(0);
32 return result;
33 }
34};Time and space complexity
O(n)
Building the child lists and the DFS each touch every node and every edge once.
O(n)
The child lists hold n - 1 edges, and the recursion stack can reach depth n for a path-shaped tree.
Other approaches
Iterative topological order from the leaves (time O(n), space O(n))
Count children per node, start a queue with the leaves and process nodes bottom up, pushing each node's chain length into its parent once all its children are done. It computes the same top two values without recursion, which avoids stack overflow on deep trees.
Common mistakes
- Skipping the DFS call for children with the same character. Their subtrees can still hold the best path, so you must recurse and only skip attaching their chain.
- Keeping only the single longest child chain, which misses paths that bend through a node.
- Measuring the answer in edges instead of nodes. The problem counts nodes, so a single node has length 1.
- Hitting Python's default recursion limit on a long chain of 10^5 nodes. Raise the limit or use the iterative version.
Frequently asked questions
How is this problem related to the diameter of a binary tree?
Both compute, at each node, the longest downward chain and combine the two best chains into a path through that node. Here a node can have many children and chains only connect across different characters.
Why do we still visit children with the same character?
Their subtree might contain a longer valid path that never touches the current node. The DFS must update the global answer inside that subtree, even though the child's chain cannot extend upward.
Can this be solved with BFS instead of DFS?
Yes. Process nodes from leaves to root using child counts, like a topological sort. Each node combines its children's results when they are all ready, which gives the same answer iteratively.