Saturday, 16 Oct 2021

# Find all substrings that are anagrams of another substring of the string S

Find all substrings that are anagrams of another substring of the string S Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at the different index.Examples:Input: S = “aba”Output: a a ab baExplanation:Following substrings are anagrams of another substring of the string S:“a”: Substring “a” is anagram of the substring “a”(= {S}).“a”: Substring “a” is anagram of the substring “a”(= {S}).“ab”: Substring “ab” is anagram of the substring “ba”(= {S, S}).“ba”: Substring “ba” is anagram of the substring “ab”(= {S, S}).Input: S = “abcd”Output: []Approach: The given problem can be solved by using Hashing by storing the anagrams of each substring of the string S and print the resultant substring. Follow the below steps to solve the given problem:Initialize a HashMap that stores all the anagrams of each substring of the string S.Generate all the possible substrings of S and for each substring, say str store the substring in the HashMap mapped with the key as the sorted string str.Traverse the HashMap and print all the strings associated with each key whose number of strings associated with each string is at least 1.Below is the implementation of the above approach:Python3  import collections  def findAnagrams(S):                Map = collections.defaultdict(list)              N = len(S)              for i in range(N):        for j in range(i, N):                                                  curr = S[i: j + 1]                                      key = “”.join(sorted(curr))                                                  Map[key].append(curr)              result = []              for vals in Map.values():                          if len(vals) > 1:                                     for v in vals:                  print(v, end =” “)        S = “aba”findAnagrams(S)Output:
ab ba a a
Time Complexity: O(N3)Auxiliary Space: O(N2)Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.