![]() |
VOOZH | about |
Given string str consists of only lowercase alphabets and an integer K, the task is to count the number of substrings of size K such that any permutation of the substring is a palindrome.
Examples:
Input: str = "abbaca", K = 3
Output: 3
Explanation:
The substrings of size 3 whose permutation is palindrome are {"abb", "bba", "aca"}.Input: str = "aaaa", K = 1
Output: 4
Explanation:
The substrings of size 1 whose permutation is palindrome are {'a', 'a', 'a', 'a'}.
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.
Time Complexity:O(N*K)
The idea is to use the Window Sliding Technique and using a frequency array of size 26.
Step-by-step approach:
Below is the implementation of the above approach:
3
Time Complexity: O(N)
Auxiliary Space: O(1)