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 a different index.
Examples:
Input: S = “aba”
Output: a a ab ba
Explanation:
Following substrings are anagrams of another substring of the string S:
- “a”: Substring “a” is anagram of the substring “a”(= {S[0]}).
- “a”: Substring “a” is anagram of the substring “a”(= {S[2]}).
- “ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]}).
- “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 printing 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:
C++
#include <bits/stdc++.h> using namespace std; // Function to find all the substrings // whose anagram exist as a different // substring in S void findAnagrams(string S) { // Stores the length of S int N = S.length(); // Stores the lists of anagrams of // each substring of S map<string, vector<string>> mp; // Generate all substrings of S for ( int i = 0; i < N; i++) { for ( int j = i; j < N; j++) { string curr = "" ; // Store the current substring // of the string S for ( int k = i; k < j + 1; k++) curr.push_back(S[k]); string key = curr; // Key is the sorted substring sort(key.begin(), key.end()); // Add the sorted substring // to the dictionary mp[key].push_back(curr); } } // Iterate over values of map for ( auto itr : mp) { // If length of list > 1 if (itr.second.size() > 1) { // Print all the strings for (string str : itr.second) cout << str << " " ; } } } // Driver Code signed main() { string S = "aba" ; findAnagrams(S); return 0; } // This code is contributed by sdeadityasharma |
Java
import java.util.*; class Main { // Function to find the anagrams of the substring public static void findAnagrams(String s) { // stores the length of s int n = s.length(); // stores the lists of anagrams of // each substring of s HashMap<String, ArrayList<String> > mp = new HashMap<String, ArrayList<String> >(); // Generate all the substrings of s for ( int i = 0 ; i < n; i++) { for ( int j = i; j < n; j++) { String curr = "" ; // Store the current substring // of the string s curr = s.substring(i, j + 1 ); String key = curr; // key is the sorted substring char [] chars = key.toCharArray(); Arrays.sort(chars); key = new String(chars); // Add the sorted substring // to the dictionary if (mp.containsKey(key)) { mp.get(key).add(curr); } else { ArrayList<String> list = new ArrayList<String>(); list.add(curr); mp.put(key, list); } } } // Iterate over the values of map ArrayList<String> result = new ArrayList<String>(); for (String itr : mp.keySet()) { if (mp.get(itr).size() > 1 ) { for (String str : mp.get(itr)) { result.add(str); } } } String res = String.join( " " , result); System.out.println(res); } public static void main(String[] args) { String s = "aba" ; findAnagrams(s); } } // this code is contributed by devendra |
Python3
# Python program for the above approach import collections # Function to find all the substrings # whose anagram exist as a different # substring 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) |
C#
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main( string [] args) { string S = "aba" ; FindAnagrams(S); } // Function to find all the substrings // whose anagram exist as a different // substring in S static void FindAnagrams( string S) { // Stores the length of S int N = S.Length; // Stores the lists of anagrams of // each substring of S Dictionary< string , List< string >> mp = new Dictionary< string , List< string >>(); // Generate all substrings of S for ( int i = 0; i < N; i++) { for ( int j = i; j < N; j++) { string curr = "" ; // Store the current substring // of the string S for ( int k = i; k < j + 1; k++) { curr += S[k]; } string key = new string (curr.ToCharArray().OrderBy(c => c).ToArray()); // Add the sorted substring // to the dictionary if (!mp.ContainsKey(key)) { mp.Add(key, new List< string >()); } mp[key].Add(curr); } } // Iterate over values of map foreach ( var itr in mp) { // If length of list > 1 if (itr.Value.Count > 1) { // Print all the strings foreach ( string str in itr.Value) { Console.Write(str + " " ); } } } } } |
Javascript
function findAnagrams(s) { // stores the length of s let n = s.length; // stores the lists of anagrams of // each substring of s mp = {}; // Generate all the substrings of s for (let i = 0; i < n; i++){ for (let j = i; j < n; j++){ let curr = "" ; // Store the current substring // of the string s curr = s.slice(i,j + 1); let key = curr; // console.log(curr); // key is the sorted substring key = key.split( '' ).sort().join( '' ); // Add the sorted substring // to the dictionary if (key in mp){ mp[key].push(curr); } else { mp[key] = [curr]; } } } // Iterate over the values of map result = []; for (let itr in mp){ if (mp[itr].length > 1){ for (let str of mp[itr]){ result.push(str); } } } result = result.join( " " ); console.log(result); } let s = "aba" ; findAnagrams(s) // This code is contributed by sdeadityasharma. |
Output:
ab ba a a
Time Complexity: O(N3 log N)
Auxiliary Space: O(N2)
Contact Us