Skip to content
Related Articles

Related Articles

Find all substrings that are anagrams of another substring of the string S
  • Last Updated : 13 Apr, 2021

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 ba
Explanation:
Following substrings are anagrams of another substring of the string S:

  1. “a”: Substring “a” is anagram of the substring “a”(= {S[0]}).
  2. “a”: Substring “a” is anagram of the substring “a”(= {S[2]}).
  3. “ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]}).
  4. “ba”: Substring “ba” is anagram of the substring “ab”(= {S[0], S[2]}).

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




# Python program for the above approach
  
import collections
  
# Function to find all the substrings
# whose anagram exist as a different
# subtring in S
def findAnagrams(S):
    
    # Stores the lists of anagrams of
    # each substring of S
    Map = collections.defaultdict(list)
      
    # Stores the length of S
    N = len(S)
      
    # Generate all substrings of S
    for i in range(N):
        for j in range(i, N):
              
            # Store the current substring
            # of the string S
            curr = S[i: j + 1]
              
            # Key is the sorted substring
            key = "".join(sorted(curr))
              
            # Add the sorted substring 
            # to the dictionary 
            Map[key].append(curr)
      
    # Store the final result
    result = []
      
    # Iterate over values of dictionary
    for vals in Map.values():
          
        # If length of list > 1
        if len(vals) > 1:
             
            # Print all the strings
            for v in vals:
                  print(v, end =" ")    
  
# Driver Code
  
S = "aba"
findAnagrams(S)
Output:
ab ba a a

Time Complexity: O(N3)
Auxiliary Space: O(N2)




My Personal Notes arrow_drop_up
Recommended Articles
Page :