#2791
Count Paths That Can Form a Palindrome in a Tree
HardHash TableBit ManipulationTreeDepth-First SearchBit ManipulationDepth-First SearchHash Map
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses bit manipulation to track character frequencies efficiently. By maintaining a bitmask for each node that represents the parity of character counts, we can quickly determine if the path can form a palindrome.
⚙️
Algorithm
4 steps- 1Step 1: Create a bitmask for each node where each bit represents the parity of the character count from the root to that node.
- 2Step 2: Use Depth-First Search (DFS) to compute the bitmask for each node.
- 3Step 3: Count how many times each bitmask appears using a hashmap.
- 4Step 4: For each bitmask, if it appears k times, it contributes k * (k - 1) / 2 valid pairs. Also, check for each bitmask with one bit flipped (to account for odd counts).
solution.py21 lines
1def countPalindromicPaths(parent, s):
2 from collections import defaultdict
3 n = len(parent)
4 count = 0
5 mask_count = defaultdict(int)
6 mask_count[0] = 1 # Empty path mask
7 def dfs(node, mask):
8 nonlocal count
9 # Update the mask for the current node
10 mask ^= (1 << (ord(s[node]) - ord('a')))
11 count += mask_count[mask] # Count pairs with the same mask
12 # Check for masks with one bit flipped
13 for i in range(26):
14 count += mask_count[mask ^ (1 << i)]
15 mask_count[mask] += 1
16 for child in range(n):
17 if parent[child] == node:
18 dfs(child, mask)
19 mask_count[mask] -= 1 # Backtrack
20 dfs(0, 0)
21 return countℹ
Complexity note: The time complexity is O(n) because we traverse each node once during the DFS, and the space complexity is O(n) due to the hashmap storing the mask counts.
- 1A string can form a palindrome if at most one character has an odd frequency.
- 2Using bit manipulation allows us to efficiently track character frequencies and their parities.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.