Find all substrings that are anagrams of another substring of the string S
Last Updated :
22 Feb, 2023
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.
Time Complexity: O(N3 log N)
Auxiliary Space: O(N2)
Similar Reads
Check if a string contains an anagram of another string as its substring Given two strings S1 and S2, the task is to check if S2 contains an anagram of S1 as its substring. Examples: Input: S1 = "ab", S2 = "bbpobac"Output: YesExplanation: String S2 contains anagram "ba" of S1 ("ba"). Input: S1 = "ab", S2 = "cbddaoo"Output: No Approach: Follow the steps below to solve the
7 min read
Count of substrings of a string containing another given string as a substring Given two strings S and T, the task is to count the number of substrings of S that contains string T in it as a substring. Examples: Input: S = "dabc", T = "ab"Output: 4Explanation: Substrings of S containing T as a substring are: S[0, 2] = âdabâS[1, 2] = âabâS[1, 3] = âabcâS[0, 3] = âdabcâ Input: S
8 min read
Sub-strings of a string that are prefix of the same string Given a string str, the task is to count all possible sub-strings of the given string that are prefix of the same string. Examples: Input: str = "ababc" Output: 7 All possible sub-string are "a", "ab", "aba", "abab", "ababc", "a" and "ab" Input: str = "abdabc" Output: 8 Approach: Traverse the string
10 min read
Different substrings in a string that start and end with given strings Given a string s and two other strings begin and end, find the number of different substrings in the string which begin and end with the given begin and end strings. Examples: Input : s = "geeksforgeeks" begin = "geeks" end = "for" Output : 1 Input : s = "vishakha" begin = "h" end = "a" Output : 2 T
9 min read
Removing string that is an anagram of an earlier string Given an array arr of strings, the task is to remove the strings that are an anagram of an earlier string, then print the remaining array in sorted order. Examples: Input: arr[] = { "geeks", "keegs", "code", "doce" }, N = 4 Output: ["code", "geeks"] Explanation: "geeks" and "keegs" are anagrams, so
7 min read