Longest Path With Different Adjacent Characters

Longest path in a tree such that no two adjacent nodes share a character — DFS combining top-two child paths per node.

Hard
Time O(n) Space O(n)
LeetCode
4 min read
topological-sort tree dfs

Problem#

Tree rooted at 0. Each node has a character. Return the longest path of nodes such that no two adjacent nodes share a character.

Examples#

  • parent = [-1,0,0,1,1,2], s = "abacbe"3

Constraints#

  • 1 <= n <= 10^5.

Approach#

DFS post-order returning the longest “downward” path from the current node. For each node, track the top-two longest paths from children with characters different from the current node. Combine for the path through this node.

Solution#

Longest Path With Different Adjacent Characters
class Solution {
public:
int longestPath(vector<int>& parent, string s) {
int n = parent.size();
vector<vector<int>> children(n);
for (int i = 1; i < n; ++i) children[parent[i]].push_back(i);
int best = 1;
function<int(int)> dfs = [&](int u) -> int {
int top1 = 0, top2 = 0;
for (int v : children[u]) {
int chainLen = dfs(v);
if (s[v] == s[u]) continue;
if (chainLen > top1) { top2 = top1; top1 = chainLen; }
else if (chainLen > top2) top2 = chainLen;
}
best = max(best, top1 + top2 + 1);
return top1 + 1;
};
dfs(0);
return best;
}
};

Editorial#

The “longest path through this node” is computed at the post-order step using top-two child chains. The recursion returns only the single longest downward chain. Children with the same character contribute 0 (effectively skipped).

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.