![]() |
VOOZH | about |
You are given a string that consists of n characters between a–z. The positions of the string are indexed 1,2,...n.
Your task is to process m operations of the following types:
Input: Each operations are in the form of "1 k x" or "2 a b".
Example:
Input: S = aybabtu, m = {{2, 3, 5}, {1, 3, 'x'}, {2, 3, 5}, {1, 5, 'x'}, {2, 3, 5}}
Output:
YES
NO
YESInput: S = "racecar", m = { {1, 2, 'a'}, {2, 0, 6}, {1, 3, 'e'}, {2, 0, 6}}
Output:
NO
NO
Approach:
The idea is to hash table to store the forward and backward representations of the string. Each character in the string is mapped with a unique prime number (hash), and the representation of a substring is the product of the hashes of its characters. This allows us to compute the representation of any substring in constant time, given the representations of its prefix and suffix.
Lets breakdown step-by-step solution:
We will do Preprocessing: We first compute the powers of a fixed hash for each position in the string, and initialize two hash tables to store the forward and backward representations of the string.
We'll Updating a Character: When the operation is to change a character, we update the forward and backward hash tables at the corresponding position. This is done by multiplying the old hash at the position by the new hash, and updating the hash tables.
Checking a Substring: When the operation is to check if a substring is a palindrome, we query the forward and backward hash tables for the substring, and adjust the hashes by the appropriate powers to align the substring with the start of the string. If the adjusted forward and backward hashes are equal, then the substring is a palindrome.
Performing the Operations: We perform each operation in the order given. For each operation, we either update a character or check a substring as described above.
Step-by-step approach:
Below is the implementation of the above approach:
YES NO YES
Time Complexity: O(n log n)
Auxiliary Space: O(n)