Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Different substrings in a string that start and end with given strings
Next article icon

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

Last Updated : 22 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  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 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)


Next Article
Different substrings in a string that start and end with given strings
author
varunkedia
Improve
Article Tags :
  • Misc
  • Strings
  • Sorting
  • Hash
  • DSA
  • anagram
  • substring
Practice Tags :
  • anagram
  • Hash
  • Misc
  • Sorting
  • Strings

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
  • Count of substrings of a string containing another given string as a substring | Set 2
    Given two strings S and T of length N and M respectively, the task is to count the number of substrings of S that contains the 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
    8 min read
  • Print all strings in the given array that occur as the substring in the given string
    Given an array of string arr[] and a string str, the task is to print all the strings in arr[] that occur as a substring in str. Example: Input: str ="geeksforgeeks", arr[] ={ "forg", "geek", "ek", "dog", "sfor"}Output: forggeekeksforExplanation: The strings "forg", "geek", "ek" and "sfor" occur as
    5 min read
  • Count subsequences in first string which are anagrams of the second string
    Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to count all the subsequences of str1 which are anagrams of str2. Examples: Input : str1 = "abacd", str2 = "abc" Output : 2 Index of characters in the 2 subsequences are: {0, 1, 3} = {a, b, c} = abc and {1, 2, 3} = {b,
    13 min read
  • Generate a string whose all K-size substrings can be concatenated to form the given string
    Given a string str of size N and an integer K, the task is to generate a string whose substrings of size K can be concatenated to form the given string. Examples: Input: str = "abbaaa" K = 2 Output: abaa Explanation: All substring of size 2 of parent string "abaa" are "ab", "ba" and "aa". After conc
    5 min read
  • Print all pairs of anagrams in a given array of strings
    Given an array of strings, find all anagram pairs in the given array. Example: Input: arr[] = {"geeksquiz", "geeksforgeeks", "abcd", "forgeeksgeeks", "zuiqkeegs"}; Output: (geeksforgeeks, forgeeksgeeks), (geeksquiz, zuiqkeegs) We can find whether two strings are anagram or not in linear time using c
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences