Naive Approach: A naive solution is to run a two-loop to generate all substrings of size K. For each substring formed, find the frequency of each character of the substring. If at most one character has an odd frequency, then one of its permutations will be a palindrome. Increment the count for the current substring and print the final count after all the operations.
Efficient Approach: This problem can be solved efficiently by using the Window Sliding Technique and using a frequency array of size 26. Below are the steps:
Store the frequency of the first K elements of the given string in a frequency array(say freq).
Using a frequency array, check the count of elements having an odd frequency. If it is less than 2, then the increment of the count of palindromic permutation.
Now, linearly slide the window ahead till it reaches the end.
At each iteration, decrease the count of the first element of the window by 1 and increase the count of the next element of the window by 1 and again check the count of elements in a frequency array having an odd frequency. If it is less than 2, then increase the count of the palindromic permutation.
Repeat the above step till we reach the end of the string and print the count of palindromic permutation.
Below is the implementation of the above approach:
In this approach, we will check all possible substrings of size K and count those substrings whose permutations are palindromic.
Initialize a count variable to zero. Loop through all substrings of size K. For each substring, generate all possible permutations. Check if any of the permutations is a palindrome. If yes, then increment the count variable. Return the count variable.
Please Login to comment...