Palindromic Path Queries in a Tree Problem
Description
LeetCode Problem 3841.
You are given an undirected tree with n nodes labeled 0 to n - 1. This is represented by a 2D array edges of length n - 1, where edges[i] = [u_i, v_i] indicates an undirected edge between nodes u_i and v_i.
You are also given a string s of length n consisting of lowercase English letters, where s[i] represents the character assigned to node i.
You are also given a string array queries, where each queries[i] is either:
"update u_i c": Change the character at nodeu_itoc. Formally, updates[u_i] = c."query u_i v_i": Determine whether the string formed by the characters on the unique path fromu_itov_i(inclusive) can be rearranged into a palindrome.
Return a boolean array answer, where answer[j] is true if the j^th query of type "query u_i v_i" can be rearranged into a palindrome, and false otherwise.
Example 1:
Input: n = 3, edges = [[0,1],[1,2]], s = "aac", queries = ["query 0 2","update 1 b","query 0 2"]
Output: [true,false]
Explanation:
- "query 0 2": Path 0 → 1 → 2 gives "aac", which can be rearranged to form "aca", a palindrome. Thus, answer[0] = true.
- "update 1 b": Update node 1 to 'b', now s = "abc".
- "query 0 2": Path characters are "abc", which cannot be rearranged to form a palindrome. Thus, answer[1] = false.
Thus, answer = [true, false].
Example 2:
Input: n = 4, edges = [[0,1],[0,2],[0,3]], s = "abca", queries = ["query 1 2","update 0 b","query 2 3","update 3 a","query 1 3"]
Output: [false,false,true]
Explanation:
- "query 1 2": Path 1 → 0 → 2 gives "bac", which cannot be rearranged to form a palindrome. Thus, answer[0] = false.
- "update 0 b": Update node 0 to 'b', now s = "bbca".
- "query 2 3": Path 2 → 0 → 3 gives "cba", which cannot be rearranged to form a palindrome. Thus, answer[1] = false.
- "update 3 a": Update node 3 to 'a', s = "bbca".
- "query 1 3": Path 1 → 0 → 3 gives "bba", which can be rearranged to form "bab", a palindrome. Thus, answer[2] = true.
Thus, answer = [false, false, true].
Constraints:
1 <= n == s.length <= 5 * 10^4edges.length == n - 1edges[i] = [u_i, v_i]0 <= u_i, v_i <= n - 1sconsists of lowercase English letters.- The input is generated such that
edgesrepresents a valid tree. 1 <= queries.length <= 5 * 10^4queries[i] = "update u_i c"orqueries[i] = "query u_i v_i"0 <= u_i, v_i <= n - 1cis a lowercase English letter.
Solution
Approach: Euler Tour + Binary Indexed Tree + Binary Lifting
Store the letters of a path as a 26-bit parity mask: bit c is 1 when letter c appears an odd number of times. A multiset of letters can be rearranged into a palindrome exactly when at most one letter has an odd count, that is, when mask & (mask - 1) == 0.
Let pref(u) be the XOR of the node masks on the path from the root to u. If w is the lowest common ancestor of u and v, the mask of the path u to v is pref(u) XOR pref(v) XOR bit[w]: the part from the root to w appears in both prefixes and cancels, so bit[w] is XORed back in.
To support updates, run an Euler tour (an iterative DFS, since the tree can be a long chain) and record an entry time tin[u] and an exit time tout[u] for each node. Put bit[u] into an XOR-based binary indexed tree at both tin[u] and tout[u]. A prefix query up to tin[u] then covers every ancestor of u once (its entry is inside the prefix, its exit is outside), while finished subtrees are counted twice and cancel. That prefix XOR is pref(u).
An update at node u XORs old ^ new into the tree at tin[u] and tout[u]. The LCA comes from binary lifting tables built once, because the tree shape never changes. Each operation costs O(log n).
Complexity:
- Time:
O((n + q) log n). - Space:
O(n log n).
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.tree = [0] * (n + 1)
def update(self, i: int, delta: int) -> None:
i += 1
while i <= self.n:
self.tree[i] ^= delta
i += i & -i
def query(self, i: int) -> int:
res = 0
while i:
res ^= self.tree[i]
i -= i & -i
return res
class Solution:
def palindromePath(
self, n: int, edges: List[List[int]], s: str, queries: List[str]
) -> List[bool]:
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
parent = [-1] * n
depth = [0] * n
tin = [0] * n
tout = [0] * n
timer = 1
pos = [0] * n
stack = [0]
while stack:
u = stack[-1]
if pos[u] < len(g[u]):
v = g[u][pos[u]]
pos[u] += 1
if v != parent[u]:
parent[v] = u
depth[v] = depth[u] + 1
tin[v] = timer
timer += 1
stack.append(v)
else:
tout[u] = timer
stack.pop()
parent[0] = 0
m = n.bit_length()
up = [parent[:]]
up[0][0] = 0
for j in range(1, m):
prev = up[-1]
up.append([prev[prev[i]] for i in range(n)])
def lca(u: int, v: int) -> int:
if depth[u] < depth[v]:
u, v = v, u
d = depth[u] - depth[v]
j = 0
while d:
if d & 1:
u = up[j][u]
d >>= 1
j += 1
if u == v:
return u
for j in range(m - 1, -1, -1):
if up[j][u] != up[j][v]:
u = up[j][u]
v = up[j][v]
return parent[u]
bit = [1 << (ord(c) - ord("a")) for c in s]
tree = BinaryIndexedTree(n)
for u in range(n):
tree.update(tin[u], bit[u])
tree.update(tout[u], bit[u])
ans = []
for q in queries:
op, a, b = q.split()
u = int(a)
if op == "update":
x = bit[u]
y = 1 << (ord(b) - ord("a"))
if x != y:
delta = x ^ y
tree.update(tin[u], delta)
tree.update(tout[u], delta)
bit[u] = y
else:
v = int(b)
w = lca(u, v)
mask = tree.query(tin[u] + 1) ^ tree.query(tin[v] + 1) ^ bit[w]
ans.append(mask & (mask - 1) == 0)
return ans