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;
void findAnagrams(string S)
{
int N = S.length();
map<string, vector<string>> mp;
for ( int i = 0; i < N; i++) {
for ( int j = i; j < N; j++) {
string curr = "" ;
for ( int k = i; k < j + 1; k++) curr.push_back(S[k]);
string key = curr;
sort(key.begin(), key.end());
mp[key].push_back(curr);
}
}
for ( auto itr : mp) {
if (itr.second.size() > 1) {
for (string str : itr.second) cout << str << " " ;
}
}
}
signed main() {
string S = "aba" ;
findAnagrams(S);
return 0;
}
|
Java
import java.util.*;
class Main
{
public static void findAnagrams(String s)
{
int n = s.length();
HashMap<String, ArrayList<String> > mp
= new HashMap<String, ArrayList<String> >();
for ( int i = 0 ; i < n; i++) {
for ( int j = i; j < n; j++) {
String curr = "" ;
curr = s.substring(i, j + 1 );
String key = curr;
char [] chars = key.toCharArray();
Arrays.sort(chars);
key = new String(chars);
if (mp.containsKey(key)) {
mp.get(key).add(curr);
}
else {
ArrayList<String> list
= new ArrayList<String>();
list.add(curr);
mp.put(key, list);
}
}
}
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);
}
}
|
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)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main( string [] args)
{
string S = "aba" ;
FindAnagrams(S);
}
static void FindAnagrams( string S)
{
int N = S.Length;
Dictionary< string , List< string >> mp = new Dictionary< string , List< string >>();
for ( int i = 0; i < N; i++)
{
for ( int j = i; j < N; j++)
{
string curr = "" ;
for ( int k = i; k < j + 1; k++)
{
curr += S[k];
}
string key = new string (curr.ToCharArray().OrderBy(c => c).ToArray());
if (!mp.ContainsKey(key))
{
mp.Add(key, new List< string >());
}
mp[key].Add(curr);
}
}
foreach ( var itr in mp)
{
if (itr.Value.Count > 1)
{
foreach ( string str in itr.Value)
{
Console.Write(str + " " );
}
}
}
}
}
|
Javascript
function findAnagrams(s)
{
let n = s.length;
mp = {};
for (let i = 0; i < n; i++){
for (let j = i; j < n; j++){
let curr = "" ;
curr = s.slice(i,j + 1);
let key = curr;
key = key.split( '' ).sort().join( '' );
if (key in mp){
mp[key].push(curr);
}
else {
mp[key] = [curr];
}
}
}
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)
|
Time Complexity: O(N3 log N)
Auxiliary Space: O(N2)
Last Updated :
22 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...