Skip to main content
Back to problems
#2246
Hard Algorithms

Longest path with different adjacent characters

Array String Tree Depth-First Search Graph Theory Topological Sort
54.0% acceptance
Feb 25, 2026
2532
61
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn longest_path(parent: Vec<i32>, s: String) -> i32 {
    let n = parent.len();
    let chars: Vec<u8> = s.bytes().collect();
    let mut children: Vec<Vec<usize>> = vec![Vec::new(); n];
    for i in 1..n {
      children[parent[i] as usize].push(i);
    }

    let mut ans = 1;
    // Iterative post-order DFS using dp: dp[node] = longest valid path from node downward
    let mut dp = vec![1i32; n];
    // Process in reverse BFS order (since parent[i] < i for 0-indexed tree? Not guaranteed)
    // Use explicit DFS with topological order
    let mut order = Vec::with_capacity(n);
    let mut stack = vec![0usize];
    while let Some(node) = stack.pop() {
      order.push(node);
      for &child in &children[node] {
        stack.push(child);
      }
    }
    // Process in reverse (leaves first)
    for &node in order.iter().rev() {
      let mut top1 = 0i32; // best child path length
      let mut top2 = 0i32; // second best
      for &child in &children[node] {
        if chars[child] != chars[node] {
          let val = dp[child];
          if val > top1 {
            top2 = top1;
            top1 = val;
          } else if val > top2 {
            top2 = val;
          }
        }
      }
      // Path through this node = top1 + top2 + 1
      ans = ans.max(top1 + top2 + 1);
      dp[node] = top1 + 1;
    }
    ans
  }
}