Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Find the size of largest subset of anagram words
Next article icon

Find the size of largest subset of anagram words

Last Updated : 08 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. 
 

Input:  ant magenta magnate tan gnamate Output: 3 Explanation Anagram strings(1) - ant, tan Anagram strings(2) - magenta, magnate,                      gnamate Thus, only second subset have largest size i.e., 3  Input:  cars bikes arcs steer  Output: 2


 


Naive approach is to generate all possible subset and iterate from largest size of subset containing all string having same size and anagram of each others. Time complexity of this approach is O(2^n m          ) where n and m are the size of array and length of string respectively.
Efficient approach is to use hashing and sorting. Sort all characters of string and store the hash value(sorted string) in map(unordered_map in C++ and HashMap in java). At last check which one is the frequency sorted word with the highest number of occurrence. 
 

C++
// C++ Program to find the size of // largest subset of anagram #include <bits/stdc++.h> using namespace std;  // Utility function to find size of // largest subset of anagram int largestAnagramSet(string arr[], int n) {      int maxSize = 0;     unordered_map<string, int> count;      for (int i = 0; i < n; ++i) {          // sort the string         sort(arr[i].begin(), arr[i].end());          // Increment the count of string         count[arr[i]] += 1;          // Compute the maximum size of string         maxSize = max(maxSize, count[arr[i]]);     }      return maxSize; }  // Driver code int main() {     string arr[] = { "ant", "magenta",                 "magnate", "tan", "gnamate" };     int n = sizeof(arr) / sizeof(arr[0]);     cout << largestAnagramSet(arr, n) << "\n";      string arr1[] = { "cars", "bikes", "arcs",                                       "steer" };     n = sizeof(arr1) / sizeof(arr[0]);     cout << largestAnagramSet(arr1, n);     return 0; } 
Java
// Java Program to find the size of // largest subset of anagram import java.util.*;  class GFG {  // Utility function to find size of // largest subset of anagram static int largestAnagramSet(String arr[], int n) {     int maxSize = 0;     HashMap<String, Integer> count = new HashMap<>();      for (int i = 0; i < n; ++i)     {          // sort the String         char temp[] = arr[i].toCharArray();         Arrays.sort(temp);         arr[i] = new String(temp);                  // Increment the count of String         if(count.containsKey(arr[i]))         {             count.put(arr[i], count.get(arr[i]) + 1);         }         else         {             count.put(arr[i], 1);         }          // Compute the maximum size of String         maxSize = Math.max(maxSize, count.get(arr[i]));     }     return maxSize; }  // Driver code public static void main(String[] args) {     String arr[] = { "ant", "magenta",                       "magnate", "tan", "gnamate" };     int n = arr.length;     System.out.println(largestAnagramSet(arr, n));      String arr1[] = { "cars", "bikes",                        "arcs", "steer" };     n = arr1.length;     System.out.println(largestAnagramSet(arr1, n)); } }  // This code is contributed by 29AjayKumar 
Python3
# Python3 Program to find the size of  # largest subset of anagram   # Utility function to find size of  # largest subset of anagram  def largestAnagramSet(arr, n) :       maxSize = 0     count = {}       for i in range(n) :          # sort the string          arr[i] = ''.join(sorted(arr[i]))           # Increment the count of string          if arr[i] in count :             count[arr[i]] += 1         else :             count[arr[i]] = 1          # Compute the maximum size of string          maxSize = max(maxSize, count[arr[i]])      return maxSize  # Driver code arr = [ "ant", "magenta", "magnate", "tan", "gnamate" ]  n = len(arr)  print(largestAnagramSet(arr, n))   arr1 = [ "cars", "bikes", "arcs", "steer" ]  n = len(arr1) print(largestAnagramSet(arr1, n))   # This code is contributed by divyeshrabadiya072019 
C#
// C# Program to find the size of // largest subset of anagram using System; using System.Collections.Generic;  class GFG {  // Utility function to find size of // largest subset of anagram static int largestAnagramSet(String []arr, int n) {     int maxSize = 0;      Dictionary<String,                 int> count = new Dictionary<String,                                             int>();     for (int i = 0; i < n; ++i)     {          // sort the String         char []temp = arr[i].ToCharArray();         Array.Sort(temp);         arr[i] = new String(temp);                  // Increment the count of String         if(count.ContainsKey(arr[i]))         {             count[arr[i]] = count[arr[i]] + 1;         }         else         {             count.Add(arr[i], 1);         }          // Compute the maximum size of String         maxSize = Math.Max(maxSize, count[arr[i]]);     }     return maxSize; }  // Driver code public static void Main(String[] args) {     String []arr = {"ant", "magenta",                      "magnate", "tan", "gnamate"};     int n = arr.Length;     Console.WriteLine(largestAnagramSet(arr, n));      String []arr1 = {"cars", "bikes",                       "arcs", "steer"};     n = arr1.Length;     Console.WriteLine(largestAnagramSet(arr1, n)); } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>  // JavaScript Program to find the size of // largest subset of anagram   // Utility function to find size of // largest subset of anagram function largestAnagramSet(arr, n) {     var maxSize = 0;      var count = new Map();      for(var i = 0; i < n; ++i)     {          // sort the String         var temp = arr[i].split('');         temp.sort();         arr[i] = temp.join('');                  // Increment the count of String         if(count.has(arr[i]))         {             count.set(arr[i], count.get(arr[i])+1);         }         else         {             count.set(arr[i], 1);         }          // Compute the maximum size of String         maxSize = Math.max(maxSize, count.get(arr[i]));     }     return maxSize; }  // Driver code var arr = ["ant", "magenta",                  "magnate", "tan", "gnamate"]; var n = arr.length; document.write(largestAnagramSet(arr, n) + "<br>"); var arr1 = ["cars", "bikes",                   "arcs", "steer"]; n = arr1.length; document.write(largestAnagramSet(arr1, n));   </script>  

Output:  

3 2


Time complexity: O(nm\log(m)          ) where m is maximum size among all of the strings 
Auxiliary space: O(n + m)
Best approach is to store the frequency array of each word. In this, we just need to iterate over the characters of the words and increment the frequency of current letter. At last, increment the count of only identical frequency array[] and take the maximum among them. This approach is best only when length of strings are maximum in comparison to the array size.
 

cpp
// C++ Program to find the size of // largest subset of anagram #include <bits/stdc++.h> using namespace std;  // Utility function to find size of // largest subset of anagram int largestAnagramSet(string arr[], int n) {     int maxSize = 0;      // Initialize map<> of vector array     map<vector<int>, int> count;      for (int i = 0; i < n; ++i) {          // Vector array to store         // frequency of element         vector<int> freq(26);          for (char ch : arr[i])             freq[ch - 'a'] += 1;          // Increment the count of         // frequency array in map<>         count[freq] += 1;          // Compute the maximum size         maxSize = max(maxSize, count[freq]);     }     return maxSize; }  // Driver code int main() {     string arr[] = { "ant", "magenta", "magnate",                               "tan", "gnamate" };     int n = sizeof(arr) / sizeof(arr[0]);     cout << largestAnagramSet(arr, n) << "\n";      string arr1[] = { "cars", "bikes", "arcs",                                       "steer" };     n = sizeof(arr1) / sizeof(arr[0]);     cout << largestAnagramSet(arr1, n);     return 0; } 
Java
// Java program for the above approach import java.util.*;  public class Main {    // Utility function to find size of   // largest subset of anagram   static int largestAnagramSet(String arr[], int n) {     int maxSize = 0;      // Initialize map<> of vector array     Map<List<Integer>, Integer> count = new HashMap<>();      for (int i = 0; i < n; ++i) {        // Vector array to store       // frequency of element       List<Integer> freq = new ArrayList<>(Collections.nCopies(26, 0));        for (char ch : arr[i].toCharArray())         freq.set(ch - 'a', freq.get(ch - 'a') + 1);        // Increment the count of       // frequency array in map<>       count.put(freq, count.getOrDefault(freq, 0) + 1);        // Compute the maximum size       maxSize = Math.max(maxSize, count.get(freq));     }     return maxSize;   }    // Driver code   public static void main(String[] args) {     String arr[] = { "ant", "magenta", "magnate", "tan", "gnamate" };     int n = arr.length;     System.out.println(largestAnagramSet(arr, n));      String arr1[] = { "cars", "bikes", "arcs", "steer" };     n = arr1.length;     System.out.println(largestAnagramSet(arr1, n));   } }  // This code is contributed by Prince 
Python3
# Python Program to find the size of # largest subset of anagram  # Utility function to find size of # largest subset of anagram def largestAnagramSet(arr, n):     maxSize = 0      # Initialize dictionary of array     count = {}     for i in range(n):                # list to store         # frequency of element         freq=[0 for i in range(26)]          for ch in arr[i]:             freq[ord(ch) - ord('a')] += 1          # Increment the count of         # frequency array in dictionary         temp = "".join(str(i) for i in freq)         if temp not in count:             count[temp] = 1         else:             count[temp] += 1          # Compute the maximum size         maxSize = max(maxSize, count[temp])     return maxSize  # Driver code arr = ["ant", "magenta", "magnate","tan", "gnamate"] n = len(arr) print(largestAnagramSet(arr, n))  arr1 = ["cars", "bikes", "arcs", "steer"] n = len(arr1) print(largestAnagramSet(arr1, n))  # This code is contributed by rag2127 
C#
// C# Program to find the size of // largest subset of anagram using System; using System.Collections.Generic; using System.Linq;  class Program {   // Utility function to find size of   // largest subset of anagram   static int largestAnagramSet(string[] arr, int n)   {     int maxSize = 0;      // Initialize Dictionary of List array     Dictionary<string, List<string>> count = new Dictionary<string, List<string>>();      for (int i = 0; i < n; ++i)     {       // Sort the string to compare with other anagrams       char[] chArr = arr[i].ToCharArray();       Array.Sort(chArr);       string sortedStr = new string(chArr);        // Increment the count of sorted string       if (!count.ContainsKey(sortedStr))         count.Add(sortedStr, new List<string>());       count[sortedStr].Add(arr[i]);        // Compute the maximum size       maxSize = Math.Max(maxSize, count[sortedStr].Count);     }     return maxSize;   }    // Driver code   static void Main(string[] args)   {     string[] arr = { "ant", "magenta", "magnate",                     "tan", "gnamate" };     int n = arr.Length;     Console.WriteLine(largestAnagramSet(arr, n));      string[] arr1 = { "cars", "bikes", "arcs",                      "steer" };     n = arr1.Length;     Console.WriteLine(largestAnagramSet(arr1, n));   } } 
JavaScript
<script>  // JavaScript Program to find the size of // largest subset of anagram  // Utility function to find size of // largest subset of anagram function largestAnagramSet(arr, n){     let maxSize = 0      // Initialize dictionary of array     let count = new Map()     for(let i = 0; i < n; i++){              // list to store         // frequency of element         let freq=new Array(26).fill(0)          for(let ch of arr[i])             freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)] += 1          // Increment the count of         // frequency array in dictionary         let temp = freq.join('')         if(count.has(temp) == false)             count.set(temp,1)         else             count.set(temp, count.get(temp)+ 1)          // Compute the maximum size         maxSize = Math.max(maxSize, count.get(temp))     }     return maxSize }  // Driver code let arr = ["ant", "magenta", "magnate","tan", "gnamate"] let n = arr.length document.write(largestAnagramSet(arr, n),"</br>")  let arr1 = ["cars", "bikes", "arcs", "steer"] n = arr1.length document.write(largestAnagramSet(arr1, n),"</br>")  // This code is contributed by shinjanpatra  </script> 
Output 3 2

Time complexity: O(nm\log(n)          ) where m is maximum size among all of the strings 
Auxiliary space: O(n + m)
 


Next Article
Find the size of largest subset of anagram words

B

bansal1232
Improve
Article Tags :
  • Misc
  • Strings
  • DSA
  • cpp-vector
  • anagram
  • cpp-unordered_map
Practice Tags :
  • anagram
  • Misc
  • Strings

Similar Reads

    Find the word with most anagrams in a given sentence
    Given a string S in the form of a sentence, the task is to find the word from the text with the maximum number of its anagrams present in the given sentence. Example: Input: S = "please be silent and listen to what the professor says" Output: silent Explanation: Only the word "silent" has an anagram
    14 min read
    Group words with same set of characters
    Given a list of words with lower cases. Implement a function to find all Words that have the same unique character set. Example: Input: words[] = { "may", "student", "students", "dog", "studentssess", "god", "cat", "act", "tab", "bat", "flow", "wolf", "lambs", "amy", "yam", "balms", "looped", "poodl
    8 min read
    Find length of the longest non-intersecting anagram Subsequence
    Given a string S of length N, find the length of the two longest non-intersecting subsequences in S that are anagrams of each other. Input: S = "aaababcd"Output: 3Explanation: Index of characters in the 2 subsequences are: {0, 1, 3} = {a, a, b} {2, 4, 5} = {a, a, b} The above two subsequences of S a
    6 min read
    Find a word with highest number of repeating characters
    Given a string which contains multiple words, our task is to find the word which has highest number of repeating characters.Examples:Input: str = "hello world programming"Output: "programming"Explanation: The word "programming" has the highest number of repeating characters, with 'r', 'g', and 'm' e
    7 min read
    Count substrings of a given string whose anagram is a palindrome
    Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
    10 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