Longest Path With Different Adjacent Characters

Find the longest path in a tree on which every two neighbouring nodes carry different letters.

A tree has n nodes, numbered 0 to n - 1, with node 0 at the top. The array parent gives the parent of each node, with parent[0] = -1, and s[i] is the letter on node i. Return the number of nodes on the longest path in which no two neighbouring nodes have the same letter.

Example 1
Input: parent = [-1,0,0,1,1,2], s = "abacbe"
Output: 3
Explanation: 3 - 1 - 0 has the letters c, b, a. Node 2 cannot join because it is 'a' like node 0.
Example 2
Input: parent = [-1,0,0,0], s = "aabc"
Output: 3
Explanation: 2 - 0 - 3 has the letters b, a, c.
Solution

The Idea

Think of a company chart, where everyone except the boss reports to exactly one person. The array parent is that chart written as numbers. In Example 1, parent[3] = 1, so node 3 hangs under node 1, and node 0, with parent -1, is at the very top. The node at the top is called the root, and the nodes right under a node are its children.

Look at the left tree in the picture below, drawn from Example 1. Each circle shows a node's letter, with its number beside it. A path walks along the lines from node to node and never visits a node twice.

The two example trees. In Example 1 the lines 0 - 2 and 1 - 4 join nodes with the same letter and are dashed; the longest path is 3 - 1 - 0. In Example 2 the line 0 - 1 joins two a nodes; the longest path 2 - 0 - 3 goes up to node 0 and turns down again.

Node 0 and node 2 are both 'a', and node 1 and node 4 are both 'b'. A path may never step between two such nodes, so the picture draws those two lines dashed and marks them "same letter". With them gone, the longest path left is 3 - 1 - 0, with the letters c, b, a: 3 nodes. The other piece, 2 - 5, has only 2.

The right tree, from Example 2, shows a path of another shape. 2 - 0 - 3 starts at node 2, goes up to node 0 and turns down again to node 3. Every path in a tree has this shape: it climbs to one highest node, then goes down. One side may be empty, as in 3 - 1 - 0, which only climbs.

So how do we find the longest path without trying every pair of start and end nodes? Look at the highest node of a path. Below it, the path is at most two chains that run straight down, each through a different child. The longest path that turns at a node uses its two longest such chains.

That turns one big search into a small question per node: how long is the longest chain that starts here and only goes down? Once every node knows that, each node adds its two best child chains and itself, and the largest total is the answer.

Solution Approach

Turning that idea into code means settling three things: how to find a node's children, what each node works out from its children's chains instead of searching from every node, and in which order to visit the nodes.

Children lists from the parent array

Which nodes are right under a given node? parent only answers the opposite question, who is above. One pass over it fixes that: for every node i other than the root, add i to the list of parent[i]. In Example 1, node 0 gets the list [1, 2], node 1 gets [3, 4] and node 2 gets [5].

Longest chain down and the best turn at each node

Why not start a search from every node and follow every valid path? Each search can visit all n nodes, and there are n of them, so the work grows like n². On a tree of 100,000 nodes that is about 1010 steps.

Instead, each node u keeps one number: the longest valid chain that starts at u and only goes down, counting u itself. The code keeps it in an array named down. A node with no children has a chain of 1, just itself.

What can node u build from its children? A child with the same letter as u cannot sit next to u, so its chain is ignored. From the other children, u keeps the two longest chains, first and second. The longest path that turns at u is then first + second + 1.

Only first + 1 goes into down[u], though. A path that comes from u's parent can continue down from u through only one child, not two. A child that was ignored still has its own turn later: node 2 in Example 1 is cut off from node 0, but the path 2 - 5 has node 2 as its highest node.

Here is Example 1 worked through. Nodes 3, 4 and 5 have no children, so each has a chain of 1. Node 2 ('a') adds node 5 ('e'), so its chain is 2. Node 1 ('b') adds node 3 ('c') and ignores node 4 ('b'), so its chain is 2 as well. Node 0 ('a') adds node 1 and ignores node 2. Its chain is 3, and the longest path that turns there has 2 + 0 + 1 = 3 nodes.

Children before parents

A node needs its children's chains before it can work out its own, so children must come first. The natural way is a method that calls itself on each child, which is called recursion. Each call waits for the calls below it, and Java keeps all of them on the call stack, a memory area of limited size.

A tree can be one long line, 0 - 1 - 2 and so on. With 100,000 nodes in a line, the recursion goes 100,000 calls deep, and with Java's default stack size a recursive version of this method stops with StackOverflowError.

Instead, list the nodes level by level: the root, then its children, then their children. This is called breadth-first order, or BFS order, after breadth-first search, the search that visits nodes in this order. Every child appears after its parent, so reading the list backwards handles every child before its parent. In Example 1 the list is 0, 1, 2, 3, 4, 5, and the nodes are handled as 5, 4, 3, 2, 1, 0.

Java Solution

The method longestPath works in these steps:

  1. First, build children, one list per node. A loop over i from 1 to n - 1 adds node i to the list of parent[i].
  2. Next, fill the array order in BFS order. It starts with the root, 0. head points at the next node to read and tail at the next free place, and every node that is read appends its children at tail.
  3. Create the array down and set best to 1, since a single node is always a valid path. Then a loop walks order backwards with k, taking the node u = order[k].
  4. For each u, first and second start at 0. An inner loop goes over the children of u, skips any child with the same letter as u, and keeps the two largest values of down in first and second.
  5. Set down[u] to first + 1, and raise best to first + second + 1 if that is larger. After the backward loop, best holds the longest path, and the method returns it.

The main method runs both examples, a tree of one node, a line of four 'a' nodes, and a line of 100,000 nodes whose letters alternate a, b, a, b.

Java
import java.util.ArrayList;
import java.util.List;

public class LongestPathWithDifferentAdjacentCharacters {

    public static int longestPath(int[] parent, String s) {
        int n = parent.length;
        List<List<Integer>> children = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            children.add(new ArrayList<>());
        }
        for (int i = 1; i < n; i++) {
            children.get(parent[i]).add(i);          // parent only points up; store it downward
        }

        int[] order = new int[n];                    // nodes level by level from the root
        int head = 0, tail = 0;
        order[tail++] = 0;
        while (head < tail) {
            for (int c : children.get(order[head++])) {
                order[tail++] = c;
            }
        }

        int[] down = new int[n];                     // longest chain from node i going down
        int best = 1;
        for (int k = n - 1; k >= 0; k--) {           // backwards: children before parents
            int u = order[k];
            int first = 0, second = 0;               // two longest chains that can join u
            for (int c : children.get(u)) {
                if (s.charAt(c) == s.charAt(u)) {
                    continue;                        // same letter: cannot sit next to u
                }
                if (down[c] > first) {
                    second = first;
                    first = down[c];
                } else if (down[c] > second) {
                    second = down[c];
                }
            }
            down[u] = first + 1;                     // only one chain can go up to the parent
            best = Math.max(best, first + second + 1);   // a path that turns at u
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(longestPath(new int[] {-1, 0, 0, 1, 1, 2}, "abacbe"));
        System.out.println(longestPath(new int[] {-1, 0, 0, 0}, "aabc"));
        System.out.println(longestPath(new int[] {-1}, "z"));
        System.out.println(longestPath(new int[] {-1, 0, 1, 2}, "aaaa"));

        int n = 100000;                             // one long line: 0 - 1 - 2 - ... - 99999
        int[] line = new int[n];
        StringBuilder letters = new StringBuilder();
        for (int i = 0; i < n; i++) {
            line[i] = i - 1;
            letters.append(i % 2 == 0 ? 'a' : 'b');
        }
        System.out.println(longestPath(line, letters.toString()));
    }
}

Running it prints:

Output
3
3
1
1
100000

Both examples give 3. In the second, the 3 comes from first + second + 1 at the root: node 2 and node 3 each bring a chain of 1, and node 1 is skipped. If best were raised only with first + 1, a chain down through one child, that path would be missed, and the method would return 2 for Example 2 instead of 3.

The next two lines are both 1. A tree of one node has a path of one node. In the line of four 'a' nodes every link joins two equal letters, so the best a path can do is a single node.

The last line, 100000, is the long line of alternating letters. Every node is on the path, and the method finishes without any deep chain of calls, because the backward loop over order replaces the recursion.

Complexity

The method makes three passes, and each one touches every node or every parent-child link a fixed number of times.

  • Time: O(n), because building the children lists, the BFS pass and the backward pass each handle every one of the n nodes once and look at each of the n - 1 parent-child links once.
  • Space: O(n), because the children lists hold n - 1 entries in all, order and down hold n each, and no recursion piles up calls on the stack.

Joining the two longest chains below a node is also how Diameter of Binary Tree finds the longest path in a binary tree.