Check for Palindrome after every character replacement Query
Given a string str and Q queries. Each query contains a pair of integers (i1, i2) and a character ‘ch’. We need to replace characters at indexes i1 and i2 with new character ‘ch’ and then tell if string str is palindrome or not. (0 <= i1, i2 < string_length)
Input : str = "geeks" Q = 2 query 1: i1 = 3 ,i2 = 0, ch = 'e' query 2: i1 = 0 ,i2 = 2, ch = 's' Output : query 1: "NO" query 2: "NO" Explanation : In query 1 : i1 = 3 , i2 = 0 ch = 'e' After replacing char at index i1, i2 str = 'e', str = 'e' string become "eeees" which is not palindrome so output "NO" In query 2 : i1 = 0 i2 = 2 ch = 's' After replacing char at index i1 , i2 str = 's', str = 's' string become "sesks" which is palindrome so output "NO" Input : str = "jasonamat" Q = 3 query 1: i1 = 3, i2 = 8 ch = 'j' query 2: i1 = 2, i2 = 6 ch = 'n' query 3: i1 = 3, i2 = 7 ch = 'a' Output : query 1: "NO" query 2: "NO" query 3: "YES"
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
A Simple solution is that for each query , we replace character at indexes (i1 & i2) with a new character ‘ch’ and then check if string is palindrome or not.
Below is implementation of above idea
3 0 e 0 2 s
Time complexity O(Q*n) (n is length of string )
An efficient solution is to use hashing. We create an empty hash set that stores indexes that are unequal in palindrome (Note: ” we have to store indexes only first half of string that are unequal “).
Given string "str" and length 'n'. Create an empty set S and store unequal indexes in first half. Do following for each query : 1. First replace character at indexes i1 & i2 with new char "ch" 2. If i1 and/or i2 are/is greater than n/2 then convert into first half index(es) 3. In this step we make sure that S contains maintains unequal indexes of first half. a) If str[i1] == str [n - 1 - i1] means i1 becomes equal after replacement, remove it from S (if present) Else add i1 to S b) Repeat step a) for i2 (replace i1 with i2) 4. If S is empty then string is palindrome else NOT
Below is C++ implementation of above idea
3 0 e 0 2 s
Time Complexity : O(Q + n) under the assumption that set insert, delete and find operations take O(1) time.
This article is contributed by Nishant_Singh(Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.