Anagram Substring Search
Anagram Substring Search
Approach 1:
The brute force approach is to check for the anagram of the given pattern at all possible
indexes i. The pattern will start at the index i in the given string.
You can match the frequency of the character of the string starting at index i in the string
s with the frequency of the character in the pat string.
Algorithm:
● Consider the Input txt[] = "BACDGABCDA" pat[] = "ABCD".
● Occurrences of the pat[] and its permutations are found at indexes 0,5,6.
● The permutations are BACD,ABCD,BCDA.
● Let's sort the pat[] and the permutations of pat[] in txt[].
● pat[] after sorting becomes : ABCD permutations of pat[] in txt[] after sorting
becomes : ABCD, ABCD,ABCD.
● So we can say that the sorted version of pat[] and sorted version of its
permutations yield the same result.
Code:
# driver code
txt = "BACDGABCDA"
pat = "ABCD"
search(pat, txt)
Output:
Found at Index 0
Found at Index 5
Found at Index 6
Time Complexity:
O(mlogm) + O( (n-m+1)(m + mlogm + m) )
The for loop runs for n-m+1 times in each iteration we build string temp, which takes
O(m) time, and sorting temp, which takes O(mlogm) time, and comparing sorted pat and
sorted substring, which takes O(m). So time complexity is O( (n-m+1)*(m+mlogm+m) )
Space Complexity:
O(m) where m is the size of pattern
Approach 2:
Harshit Sachan
The only difference between the first and this method is that the frequency
matching is optimized from O(nlog(n)) to O(1). In this approach, you need to use
two count arrays:
1. The first count array store frequencies of character in pattern.
2. The second count array stores frequencies of characters in current window of
text.
The important thing to note is, time complexity to compare two count arrays is O(1) as
the number of elements in them are fixed (independent of pattern and text sizes).
Following are steps of this algorithm.
1. Store count of frequencies of pattern in first count array countP[]. Also store
counts of frequencies of characters in first window of text in array countTW[].
2. Now run a loop from i = M to N-1. Do following in loop.
a. If the two count arrays are identical, we found an occurrence.
b. Increment count of current character of text in countTW[].
c. Decrement count of first character in previous window in countWT[].
3. The last window is not checked by above loop, so explicitly check it.
MAX = 256
M = len(pat)
N = len(txt)
countTW = [0]*MAX
for i in range(M):
(countP[ord(pat[i])]) += 1
(countTW[ord(txt[i])]) += 1
Output:
Found at Index 0
Found at Index 5
Found at Index 6
Time Complexity:
O(n) where n is the size of txt
Space Complexity:
O(n) where n is the size of txt
Conclusion:
In this article we learn about two different approaches to solve the Anagram Substring
Problem using python. We discuss the algorithms and time and space complexity of each
al;loiu65gorithm. Also the pros and cons of both approaches.