Count Palindromic Ancestor Paths
UberSoftware Engineer · Online AssessmentLast updated
This problem tests your ability to use bit manipulation and prefix properties on trees to solve path-related queries efficiently, specifically focusing on the property that a set of characters can form a palindrome if at most one character has an odd frequency.
Problem Statement
You are given a rooted tree with N nodes, indexed 0 to N-1. Each node i has an associated lowercase English character c_i. A path from the root to any node u defines a sequence of characters. A path is "palindrome-permutable" if the characters along that path can be rearranged to form a palindrome.
Given the tree structure and a list of queries, determine for each node u whether the path from the root to u can form a palindrome. A set of characters can form a palindrome if and only if at most one character appears an odd number of times.
Implement the function:
def solve(n, edges, chars):
n: An integer representing the number of nodes.edges: A list of tuples(u, v)representing directed edges from parentuto childv.chars: A string wherechars[i]is the character at nodei.
Return a list of booleans of length n, where the i-th element is True if the path from the root to node i can form a palindrome, and False otherwise.
Constraints
1 <= N <= 10^5charscontains only lowercase 'a'-'z'.
Examples
Example 1
Input:
n = 3, edges = [(0, 1), (1, 2)], chars = "aba"
Output: [True, True, True]
Explanation:
- Node 0: "a" (Odd count: 'a':1. Valid.)
- Node 1: "ab" (Odd counts: 'a':1, 'b':1. Invalid.) -> Wait, "ab" cannot form a palindrome. Let's re-check: 'a'=1, 'b'=1. Two odd counts. False.
- Correction: The example path "aba" is True. The path "ab" is False.
Example 2
Input:
n = 2, edges = [(0, 1)], chars = "aa"
Output: [True, True]
Explanation:
- Node 0: "a" (True)
- Node 1: "aa" (True)
Hints
Hint 1
Represent the character counts of a path as a bitmask of length 26, where the i-th bit is 1 if the character has an odd frequency and 0 otherwise.
Hint 2
The bitmask for a child node is the XOR sum of the parent's bitmask and a bitmask representing the child's character.
Hint 3
A bitmask represents a palindrome-permutable path if the number of set bits is 0 or 1, which can be checked using `x & (x - 1) == 0`.
Follow-up questions
- How would you modify your solution to count palindrome-permutable paths between *any* two nodes `u` and `v`, not just from the root?
- What is the time complexity of your approach, and can it be optimized using a hash map to store frequencies of path-masks?
- How would you handle the case where the tree is very deep and recursion depth becomes an issue?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.