Count Paths That Can Form a Palindrome in a Tree — LeetCode 2791 Python Solution
HardBit ManipulationTreeDepth-First SearchDynamic ProgrammingBitmask
- Problem
- #2791
- Pattern
- Bit Manipulation
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1.
Example
- Input
- parent = [-1,0,0,1,1,2], s = "acaabc"
- Output
- 8
- Explanation
- The valid pairs are:
Python solution
Python
class Solution:
def countPalindromePaths(self, parent: List[int], s: str) -> int:
def dfs(i: int, xor: int):
nonlocal ans
for j, v in g[i]:
x = xor ^ v
ans += cnt[x]
for k in range(26):
ans += cnt[x ^ (1 << k)]
cnt[x] += 1
dfs(j, x)
n = len(parent)
g = defaultdict(list)
for i in range(1, n):
p = parent[i]
g[p].append((i, 1 << (ord(s[i]) - ord('a'))))
ans = 0
cnt = Counter({0: 1})
dfs(0, 0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2791. Count Paths That Can Form a Palindrome in a Tree is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2791. Count Paths That Can Form a Palindrome in a Tree?
- LeetCode 2791. Count Paths That Can Form a Palindrome in a Tree is rated Hard on LeetCode.
- What topics does LeetCode 2791. Count Paths That Can Form a Palindrome in a Tree cover?
- LeetCode 2791. Count Paths That Can Form a Palindrome in a Tree is tagged Bit Manipulation, Tree, Depth-First Search, Dynamic Programming and Bitmask on LeetCode.