VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-substring-can-be-palindromic-by-replacing-k-characters-for-q-queries/

⇱ Check if a substring can be Palindromic by replacing K characters for Q queries - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a substring can be Palindromic by replacing K characters for Q queries

Last Updated : 12 Jul, 2025

Given a string str and Q queries in form of [L, R, K], the task is to find whether characters from the string from [L, R] with at most K changes are allowed can be rearranged to make string palindromic or not. For each query, print "YES" if it can become a palindromic string else print "NO".
Examples:

Input: str = "GeeksforGeeks", Q = { { 1, 5, 3 }, { 5, 7, 0 }, { 8, 11, 3 }, {3, 10, 5 }, { 0, 9, 5 } } 
Output:
YES 
NO 
YES 
YES 
YES 
Explanation:
queries[0] : substring = "eeksf", could be changed to "eekee" which is palindrome. 
queries[1] : substring = "for", is not palindrome and can't be made palindromic after replacing atmost 0 character.. 
queries[2] : substring = "Geek", could be changed to "GeeG" which is palindrome. 
queries[3] : substring = "ksforGee", could be changed to "ksfoofsk" which is palindrome. 
queries[4] : substring = "GeeksforGe", could be changed to "GeeksskeeG" which is palindrome.
Input: str = "abczwerte", Q = { { 3, 7, 4 }, { 1, 8, 10 }, { 0, 3, 1 } } 
Output:
YES 
YES 
NO 

Approach: This problem can be solved using Dynamic Programming.  

  • Create a 2D matrix (say dp[i][j]) where dp[i][j] denotes the count of ith character in the substring str[0...j].
  • Below is the recurrence relation for the above approach: 
    • If str[i] is equals to str[j], then dp[i][j] = 1 + dp[i][j-1].
    • If str[i] is not equals to str[j], then dp[i][j] = dp[i][j-1].
    • if j equals 0, then dp[i][j] would be one of the first characters which are equal to ith characters.
  • For each query, find out the count of each character in the substring str[L...R] by the simple relation:
count = dp[i][right] - dp[i][left] + (str[left] == i + 'a').
  • Get the count of unmatched pairs.
  • Now we need to convert the half unmatched characters to the remaining characters. If the count of half unmatched characters is less than or equals to K then, print "YES" else print "NO".

Below is the implementation of the above approach: 


Output
YES
NO
YES
YES
YES

Time Complexity: O(26*N), where N is the length of the string. 
Auxiliary Space: O(26*N), where N is the length of the string. 

Comment