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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Counter to find the size of largest subset of anagram words
Next article icon

Python Counter to find the size of largest subset of anagram words

Last Updated : 27 Jul, 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. Examples:

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., 3Input:
cars bikes arcs steer
Output: 2

Python Counter to find the size of largest subset of anagram words

We have existing solution for this problem please refer Find the size of largest subset of anagram words link. We can solve this problem quickly in python using Counter() method. Approach is very simple,

  1. Split input string separated by space into words.
  2. As we know two strings are anagram to each other if they contain same character set. So to get all those strings together first we will sort each string in given list of strings.
  3. Now create a dictionary using Counter method having strings as keys and their frequencies as value.
  4. Check for maximum value of frequencies, that will be the largest sub-set of anagram strings.
Python3
# Function to find the size of largest subset  # of anagram words from collections import Counter  def maxAnagramSize(input):      # split input string separated by space     input = input.split(" ")      # sort each string in given list of strings     for i in range(0,len(input)):          input[i]=''.join(sorted(input[i]))      # now create dictionary using counter method     # which will have strings as key and their      # frequencies as value     freqDict = Counter(input)      # get maximum value of frequency     print (max(freqDict.values()))  # Driver program if __name__ == "__main__":     input = 'ant magenta magnate tan gnamate'     maxAnagramSize(input) 

Output:

3

Python Counter to find the size of largest subset of anagram words Using dictionary

Approach

it uses a dictionary to group words with the same set of characters. However, instead of using a frozen set of character counts as the key, it sorts the characters in each word and uses the resulting string as the key.

Algorithm

1. Create an empty dictionary called anagram_dict.
2. Loop through each word in the input list words:
a. Sort the characters in the word and store the result as a string.
b. If the sorted string is not already in the dictionary, add it as a key and set its value to an empty list.
c. Append the original word to the list of values for the corresponding key in the dictionary.
3. Find the maximum length of the values in the dictionary.
4. Return the maximum length.

Python3
def largest_anagram_subset_size(words):     anagram_dict = {}     for word in words:         sorted_word = ''.join(sorted(word))         if sorted_word not in anagram_dict:             anagram_dict[sorted_word] = []         anagram_dict[sorted_word].append(word)     max_count = max([len(val) for val in anagram_dict.values()])     return max_count  words = ['ant', 'magenta', 'magnate', 'tan', 'gnamate'] print(largest_anagram_subset_size(words))  

Output
3 

Time complexity: O(n * k log k) where n is the number of words and k is the maximum length of a word in the list. This is because for each word, we need to sort its characters, which takes O(k log k) time, and we do this n times for each word in the input list

Auxiliary Space: O(n * k) where n is the number of words and k is the maximum length of a word in the list. This is because we use a dictionary to store the anagram groups, and each word in the list may need to be stored in the dictionary with its sorted characters as the key. The size of each value list in the dictionary can also be up to n, the size of the input list. Therefore, the total space required is proportional to n times k.

Python Counter to find the size of largest subset of anagram words Using lambda

We need to find the size of the largest subset of anagram words in the given list of words. We can use the collections.Counter class to create a dictionary of the counts of each character in a given string. We then compare the Counter objects of each word in the list with the Counter objects of every other word in the list to determine if they are anagrams. Finally, we find the maximum count of anagrams for any word in the list to determine the size of the largest subset of anagram words.

Algorithm

1. Initialize max_anagrams to 0.
2. For each word x in the list of words:
a. Create a generator expression that maps each word y in the list of words to 1 if it is an anagram of x, and 0 otherwise.
b. Sum the resulting list of 1's and 0's to obtain the number of anagrams for x.
c. Update max_anagrams to the maximum of its current value and the number of anagrams for x.
3. Output max_anagrams.

Python3
from collections import Counter  words = ['cars', 'bikes', 'arcs', 'steer']  max_anagrams = max(     list(         map(             lambda x: sum(                 map(                     lambda y: Counter(y) == Counter(x),                      words                 )             ),             words         )     ),     default=0 )  print(max_anagrams) 

Output
2 

Time complexity: O(n^2 * k), where n is the length of the list of words and k is the maximum number of distinct characters in a word.

Auxiliary Space: O(n * k), where n is the length of the list of words and k is the maximum number of distinct characters in a word.


Next Article
Python Counter to find the size of largest subset of anagram words

S

Shashank Mishra
Improve
Article Tags :
  • Python
  • DSA
  • anagram
Practice Tags :
  • anagram
  • python

Similar Reads

    Find the size of largest subset of anagram words
    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 ea
    9 min read
    Using Counter() in Python to find minimum character removal to make two strings anagram
    Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams
    3 min read
    Find the k most frequent words from data set in Python
    The goal is to find the k most common words in a given dataset of text. We'll look at different ways to identify and return the top k words based on their frequency, using Python.Using collections.Countercollections.Counter that works like a dictionary, but its main job is to count how many times ea
    3 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
    Python | Words extraction from set of characters using dictionary
    Given the words, the task is to extract different words from a set of characters using the defined dictionary. Approach: Python in its language defines an inbuilt module enchant which handles certain operations related to words. In the approach mentioned, following methods are used. check() : It che
    3 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