VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-k-size-substrings-having-palindromic-permutations/

⇱ Count of K-size substrings having palindromic permutations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of K-size substrings having palindromic permutations

Last Updated : 15 Jul, 2025

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:
Explanation:
The substrings of size 3 whose permutation is palindrome are {"abb", "bba", "aca"}.

Input: str = "aaaa", K = 1 
Output:
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:

  • 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:


Output
3

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment
Article Tags: