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 parentparent[0] = -1s[i]
Example 1
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
Output: 3
Explanation: 2 - 0 - 3 has the letters b, a, c.
The Idea
Think of a company chart, where everyone except the boss reports to exactly one person. The array parentparent[3] = 1
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.
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? parentparent[i]
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
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, firstsecondfirst + second + 1
Only first + 1down[u]
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
- First, build
, one list per node. A loop over i from 1 to n - 1 adds node i to the list ofchildren .parent[i] - Next, fill the array
in BFS order. It starts with the root, 0.order points at the next node to read andhead at the next free place, and every node that is read appends its children attail .tail - Create the array
and setdown to 1, since a single node is always a valid path. Then a loop walksbest backwards withorder , taking the nodek .u = order[k] - For each
,u andfirst start at 0. An inner loop goes over the children ofsecond , skips any child with the same letter asu , and keeps the two largest values ofu indown andfirst .second - Set
todown[u] , and raisefirst + 1 tobest if that is larger. After the backward loop,first + second + 1 holds the longest path, and the method returns it.best
The main
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:
3
3
1
1
100000
Both examples give 3. In the second, the 3 comes from first + second + 1bestfirst + 1
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
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,
andorder hold n each, and no recursion piles up calls on the stack.down
Joining the two longest chains below a node is also how