This solution looks good, but like standard Rabin Karp, the worst case time complexity of this solution is O(mn). For every character of text, we can add the current character to hash value and subtract the first character of previous window. For exampl, we can keep the hash value as sum of ASCII values of all characters under modulo of a big prime number. The idea is to modify Rabin Karp Algorithm. Space Complexity : O(m) As we are using Extra space for strings temp and sortedpat Total Time complexity : O(mlogm) + O( (n-m+1)(m + mlogm + m) ) So time complexity is 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). Time Complexity : O(mlogm) + O( (n-m+1)(m + mlogm + m) ) If they are equal then that particular substring is the permutation of the pat, else not. INTUITION: The idea is to consider all the substrings of the txt with are of lengths equal to the length of pat and check whether the sorted version of substring is equal to the sorted version of pat. So we can say that the sorted version of pat and sorted version of its Permutations of pat in txt after sorting becomes : ABCD, ABCD,ABCD. Let's sort the pat and the permutations of pat in txt. Occurrences of the pat and its permutations are found at indexes 0,5,6. Therefore, we cannot directly apply standard pattern searching algorithms like KMP, Rabin Karp, Boyer Moore, etc.Ĭonsider the Input txt = "BACDGABCDA" pat = "ABCD". This problem is slightly different from the standard pattern searching problem, here we need to search for anagrams as well. ISRO CS Syllabus for Scientist/Engineer Examġ) Input: txt = "BACDGABCDA" pat = "ABCD"Ģ) Input: txt = "AAABABAA" pat = "AABA"įound at Index 4 We strongly recommend that you click here and practice it, before moving on to the solution.ISRO CS Original Papers and Official Keys.GATE CS Original Papers and Official Keys.