expertfunda logo Top Interview Questions Binary Tree Binary Search Tree Graph Our Courses

2246. Longest Path With Different Adjacent Characters

2246. Longest Path With Different Adjacent Characters

Understanding the Longest Path With Different Adjacent Characters

In this article, we’ll dive deep into an elegant tree traversal problem that appears frequently in coding interviews and algorithm challenges. The problem is known as "Longest Path With Different Adjacent Characters". The task may look complex at first, but with the right strategy and understanding of depth-first search (DFS), it becomes an engaging problem to solve.

Problem Statement

You're given a tree represented as a list called parent[] where parent[i] denotes the parent of the ith node. The root node has no parent, and hence, its value in the parent array is -1. Also, you're given a string s where each character corresponds to the value assigned to each node.

Your goal is to return the length of the longest path in the tree such that no two adjacent nodes on the path have the same character.

Example:


Input: parent = [-1, 0, 0, 1, 1, 2], s = "abacbe"
Output: 3
Explanation: The longest path is: 0 → 1 → 3 or 0 → 2 → 5.

Key Observations

  • We are dealing with a tree, so there are no cycles.
  • We need a way to explore every node and its children, so DFS is the most natural fit.
  • While exploring children, we want to skip those which have the same character as the current node.
Important: We’re not just looking at edges, we’re checking for consecutive nodes having different characters!

Approach: Using DFS (Depth First Search)

We start from the root node (usually node 0) and traverse down the tree recursively. At each node:

  1. We visit its children and compute the longest path for each child.
  2. If a child has a different character, we consider it for our result.
  3. We track the top two longest valid paths among all children, because the longest path might go through the current node (i.e., left child → current node → right child).

This approach allows us to accumulate maximum valid path lengths efficiently.

Java Code Implementation


class Solution {
    private int maxPath = 0;
    
    public int longestPath(int[] parent, String s) {
        int n = parent.length;
        List<List<Integer>> tree = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            tree.add(new ArrayList<>());
        }
        
        for (int i = 1; i < n; i++) {
            tree.get(parent[i]).add(i);
        }

        dfs(0, tree, s);
        return maxPath;
    }

    private int dfs(int node, List<List<Integer>> tree, String s) {
        int longest = 0, secondLongest = 0;
        
        for (int child : tree.get(node)) {
            int childLen = dfs(child, tree, s);
            if (s.charAt(child) != s.charAt(node)) {
                if (childLen > longest) {
                    secondLongest = longest;
                    longest = childLen;
                } else if (childLen > secondLongest) {
                    secondLongest = childLen;
                }
            }
        }
        
        maxPath = Math.max(maxPath, longest + secondLongest + 1);
        return longest + 1;
    }
}

Walkthrough Example

Let’s go through the input example: parent = [-1, 0, 0, 1, 1, 2], s = "abacbe"

  1. Start from root node 0 ('a')
  2. Explore child 1 ('b') and child 2 ('a')
  3. From child 1, explore its children 3 ('a') and 4 ('c')
  4. Valid path: 0('a') → 1('b') → 4('c') = length 3
  5. Valid path: 0('a') → 2('a') → 5('e') is invalid at 2 (same char as 0)

Final answer: 3

Time and Space Complexity

Time Complexity: O(n)

We visit every node exactly once and explore its children in constant time. The DFS takes O(n) time overall.

Space Complexity: O(n)

We use a tree (adjacency list), which consumes O(n) space. Additionally, the recursion stack for DFS is O(h), where h is the height of the tree, which is O(n) in worst-case (skewed tree).

Why DFS Works Well

DFS allows us to dive deep into the tree and bubble the information back up. In our case, we need to know the longest valid child-paths to compute the longest combined path passing through the current node. DFS is ideal here because:

  • It processes child nodes before their parents (postorder traversal), which is perfect for aggregating results.
  • It avoids redundant computations — we visit each node once and build the solution bottom-up.

Alternative Approaches?

Some might think of a BFS approach, but BFS is more suitable for level-based or shortest path problems. Since we’re dealing with aggregating path lengths and combining child results, BFS would require extra overhead and would be less elegant.

Optimizations

  • Use arrays instead of ArrayList if node count is fixed and known in advance (for performance).
  • Use memoization if subtrees are reused (though in trees, this is rare due to acyclic nature).
  • Avoid building the tree if you can directly use parent[] to access children (but readability suffers).

Interview Tips

  • Clarify that the input is a tree (no cycles).
  • Make sure to ask if the character comparison is case-sensitive.
  • Explain why DFS is your preferred choice and how you’ll track the result (using a global variable).
  • Walk through one example verbally before writing code.

Final Thoughts

The "Longest Path With Different Adjacent Characters" problem is an excellent test of your recursive thinking, understanding of trees, and character comparison logic. It’s elegant because it teaches you how to:

  • Combine logic with tree structure traversal
  • Utilize DFS effectively to return multiple values upward
  • Think about path composition across parent-child relationships

Practice similar problems like Diameter of a Tree, Longest Univalue Path, and Tree Depth to solidify this technique.

Remember, clean recursive logic with careful tracking of paths can turn even intimidating problems into a step-by-step process. This one is a classic example.


Happy coding and keep practicing tree-based problems — they show up in almost every major technical interview!