Problem solution · Java

Count Paths That Can Form a Palindrome in a Tree

Count Paths That Can Form a Palindrome in a Tree: a Java solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
40 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Count Paths That Can Form a Palindrome in a Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 40 lines of Java from the credited upstream file 2791.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • 4 loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCount Paths That Can Form a Palindrome in a Tree · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public long countPalindromePaths(List<Integer> parent, String s) {    // A valid (u, v) has at most 1 letter with odd frequency on its path. The    // frequency of a letter on the u-v path is equal to the sum of its    // frequencies on the root-u and root-v paths substract twice of its    // frequency on the root-LCA(u, v) path. Considering only the parity    // (even/odd), the part involving root-LCA(u, v) can be ignored, making it    // possible to calculate both parts easily using a simple DFS.    List<Integer>[] tree = new List[parent.size()];     for (int i = 0; i < parent.size(); ++i)      tree[i] = new ArrayList<>();     for (int i = 1; i < parent.size(); ++i)      tree[parent.get(i)].add(i);     return dfs(tree, 0, 0, s, new HashMap<>(Map.of(0, 1)));  }   // mask := 26 bits that represent the parity of each character in the alphabet  // on the path from node 0 to node u  private long dfs(List<Integer>[] tree, int u, int mask, String s,                   Map<Integer, Integer> maskToCount) {    long res = 0;    if (u > 0) {      mask ^= 1 << (s.charAt(u) - 'a');      // Consider any u-v path with 1 bit set.      for (int i = 0; i < 26; ++i)        if (maskToCount.containsKey(mask ^ (1 << i)))          res += maskToCount.get(mask ^ (1 << i));      // Consider u-v path with 0 bit set.      res += maskToCount.getOrDefault(mask ^ 0, 0);      maskToCount.merge(mask, 1, Integer::sum);    }    for (final int v : tree[u])      res += dfs(tree, v, mask, s, maskToCount);    return res;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗