Count Paths That Can Form a Palindrome in a Tree - Problem
Imagine you have a tree network where each connection (edge) is labeled with a character. Your mission is to find all pairs of nodes where the path between them contains characters that can be rearranged to form a palindrome!
You're given:
- A tree with
nnodes (numbered 0 to n-1) rooted at node 0 - An array
parentwhereparent[i]is the parent of nodei - A string
swheres[i]is the character on the edge between nodeiand its parent
Goal: Count all pairs (u, v) where u < v and the characters on the path from u to v can be rearranged to form a palindrome.
Key Insight: A string can form a palindrome if and only if at most one character appears an odd number of times!
Input & Output
example_1.py — Basic Tree
$
Input:
parent = [-1,0,0,1,1,2], s = "abaaab"
›
Output:
10
💡 Note:
Tree has edges with characters a,b,a,a,b. Pairs like (0,1) have path 'a' which can form palindrome. Multiple valid pairs exist where characters can be rearranged to form palindromes.
example_2.py — Simple Chain
$
Input:
parent = [-1,0,1], s = "aba"
›
Output:
3
💡 Note:
Tree: 0-a-1-b-2. Valid pairs: (0,1) path='a', (1,2) path='b', (0,2) path='ab'. All can form palindromes since single chars and pairs with different chars work.
example_3.py — No Valid Pairs
$
Input:
parent = [-1,0,1], s = "abc"
›
Output:
2
💡 Note:
Tree: 0-a-1-b-2. Pairs (0,1) has path 'a', (1,2) has path 'b' - both single characters can form palindromes. Pair (0,2) has path 'ab' with 2 different odd characters, so cannot form palindrome.
Constraints
- n == parent.length == s.length
- 1 ≤ n ≤ 105
- 0 ≤ parent[i] ≤ n - 1 for all i ≥ 1
- parent[0] == -1
- parent represents a valid tree
- s consists of only lowercase English letters
- s[0] can be any character since it's ignored
Visualization
Tap to expand
Understanding the Visualization
1
Build Network Map
Convert parent array into adjacency list representing the tree structure
2
Start Journey
Begin DFS from root with bitmask=0, tracking character frequency parity
3
Check Compatibility
At each node, count paths that can combine with current path to form palindrome
4
Update Registry
Add current path's bitmask to hashmap for future compatibility checks
5
Continue Exploration
Recurse to children with updated bitmasks representing new character patterns
Key Takeaway
🎯 Key Insight: Using bitmasks to represent character frequency parity allows us to detect palindrome compatibility in O(1) time using XOR operations, making the overall solution optimal at O(n×26).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code