How to find the number of substrings that are anagrams of palindromes in a string in linear time?

To find the number of substrings that are anagrams of palindromes in a string in linear time, you can use a sliding window approach with a hashmap (frequency counter). This method runs in linear time complexity O(n), where n is the length of the input string. Here’s a step-by-step explanation of the algorithm:

Initialize a counter variable to keep track of the number of anagramic palindrome substrings found.
Initialize an empty hashmap to store the frequency of characters within the sliding window.
Start iterating through the string with two pointers (left and right) to create a sliding window. The window will represent potential substrings.
For each position of the right pointer, update the hashmap with the frequency of the character encountered.
Keep track of the number of characters with odd frequencies within the window. These characters are potential centers of palindrome substrings.
When the window size becomes greater than a certain length (determined by the problem’s constraints), start moving the left pointer to reduce the window size.
While moving the left pointer, adjust the hashmap accordingly (decrement the character frequency).
After moving the left pointer, check if the current window forms an anagram of a palindrome. This happens when there are at most one character with an odd frequency.
If the condition in step 8 is satisfied, increment the counter variable.
Continue the process until the right pointer reaches the end of the string.
Here’s a Python function implementing the algorithm:

def count_anagramic_palindromes(s):
    n = len(s)
    counter = 0
    char_freq = {}
    odd_count = 0
    window_size = 0

    for right in range(n):
        # Update the character frequency in the hashmap
        char_freq[s[right]] = char_freq.get(s[right], 0) + 1

        # Check if the current character has an odd frequency
        if char_freq[s[right]] % 2 == 1:
            odd_count += 1
            odd_count -= 1

        # Calculate the current window size
        window_size = right + 1

        # Move the left pointer and adjust the hashmap
        if window_size > k:
            char_freq[s[right - window_size]] -= 1
            if char_freq[s[right - window_size]] % 2 == 0:
                odd_count -= 1

        # Check if the window forms an anagram of a palindrome
        if odd_count <= 1:
            counter += 1

    return counter

Nilesh Raut Edited question August 3, 2023