Given a string S, the task is to check if S contains a pair of substrings of length K which are anagrams of each other and doesn’t contain the character X in them. If no such substring exists, print -1.
Input: S = “geeksforgeeks”, X = ‘f’, K = 5
Output: geeks geeks
Substrings “geeks” and “geeks” are anagrams of each other and does not contain ‘f’.
Input: S = “rotator”, X = ‘a’, K = 3
Output: rot tor
Substrings “rot” and “tor” are anagrams of each other and does not contain ‘a’.
The idea is to generate prefix sum on the basis of characters. Follow the steps below to solve the problem:
- Iterate over the string and genertae frequencies of substrings by using the prefix sum array.
- If a substring with same frequency of characters is already present in the HashMap.
- Otherwise, store the frequency of characters of the substring with the current substring in the HashMap, if the frequency of the character X in the substring is 0.
Below is the implementation of the above approach:
Time Complexity: O(N*26)
Auxiliary Space: O(N*26)