Palindromic Path Queries in a Tree

You are provided with an unrooted, undirected tree containing n vertices, labeled from 0 to n - 1. The tree's connections are defined by a 2D array edges of length n-1, where edges[i] = [u, v] indicates a bidirectional link between vertex u and vertex v.

Additionally, every vertex holds a lowercase English character. The initial characters are given as a string s of length n, meaning vertex i holds the character s[i].

Your task is to process a list of queries of two distinct types:

  • "update u c": Replace the character currently at vertex u with the lowercase letter c.
  • "query u v": Extract the collection of characters along the unique simple path connecting vertex u and vertex v (inclusive). Determine if these characters can be shuffled to read the exact same forwards and backwards (i.e., form a valid palindrome).

Return an array of boolean values representing the answers to all "query u v" operations, maintaining the order in which they appear in the input.

Example 1:

Input: n = 4, edges = [[0,1],[0,2],[0,3]], s = "abaa", queries = ["query 1 2", "update 0 c", "query 1 2"]

Output: [true, false]

Explanation:

Initial path 1 → 0 → 2 is "baa", which rearranges to palindrome "aba". After updating node 0 to 'c', the path becomes "bca", which cannot form a palindrome.

Example 2:

Input: n = 3, edges = [[0,1],[1,2]], s = "xyz", queries = ["query 0 2", "update 0 x", "update 1 x", "update 2 x", "query 0 2"]

Output: [false, true]

Explanation:

Path 0 → 2 starts as "xyz" (false). Changing all three nodes to 'x' makes the path "xxx", which is a valid palindrome.

Now Your Turn!

Pick the correct output for the given input

Input: n = 5, edges = [[0,1],[1,2],[1,3],[3,4]], s = "ababa", queries = ["query 2 4"]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n == s.length <= 5 * 104
  • edges.length == n - 1
  • edges[i] = [u, v]
  • 0 <= u, v <= n - 1
  • s consists of lowercase English letters.
  • The input guarantees that edges represents a valid tree.
  • 1 <= queries.length <= 5 * 104
  • queries[i] is either "update u c" or "query u v".
  • c is a lowercase English letter.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
vector<bool> palindromicPathQueries(int n, vector<vector<int>>& edges, string s, vector<string>& queries) {
}
};
Test Case

Input:

Edges
N
Queries
S