The palindrome condition is the part that trips you up first.
Use a parity bitmask (26 bits) to represent character counts modulo 2 along root-to-node paths. A substring from node u to ancestor v is palindrome-permutable iff the XOR of masks from root to u and root to v (exclusive) has at most one set bit. For each query node, count ancestors v (including u) where the XOR mask has popcount ≤ 1, using a DFS with a hash map of mask frequencies along the current path.
Pro tip: Mention that the parity mask approach reduces the palindrome condition to a bitwise XOR and popcount check, which is O(1) per ancestor. Also note that using a hash map during DFS avoids O(N) per query, achieving O(N + Q) total time.
Root the tree at node 0. Compute a 26-bit parity mask for each node representing character counts modulo 2 from root to that node.
For a query node u and ancestor v, the substring from v to u is palindrome-permutable iff mask[u] XOR mask[parent(v)] has at most one set bit (popcount ≤ 1).
During DFS, maintain a hash map counting occurrences of each mask along the current root-to-node path. For each node u, count ancestors v where mask[u] XOR mask[parent(v)] has popcount ≤ 1.
For each query node u, the answer is the count computed during DFS. Store answers in an array indexed by node.
Time O(N + Q) with O(N) space for masks and hash map. Each node processed once, each query answered in O(1).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.