Python Counter to find the size of largest subset of anagram words (original) (raw)

Last Updated : 30 Oct, 2025

Given an array of strings containing lowercase letters, the task is to find the size of the largest subset of words that are anagrams of each other. Two strings are said to be anagrams if they contain the same characters, only in a different order.

**Example:

Input: ant magenta magnate tan gnamate
Output: 3

**Explanation:

Using collections.Counter

This approach leverages the Python Counter() class to count word frequencies after sorting the letters of each word.

Algorithm

  1. Split the input string into a list of words.
  2. Sort the characters in each word (to make anagram words identical).
  3. Use Counter() to count how many times each sorted string appears.
  4. The highest frequency gives the size of the largest subset of anagram words.

**Code:

Python `

from collections import Counter

def maxAnagramSize(input_str): words = input_str.split(" ")

for i in range(len(words)):
    words[i] = ''.join(sorted(words[i]))

freqDict = Counter(words)

print(max(freqDict.values()))

if name == "main": input_str = 'ant magenta magnate tan gnamate' maxAnagramSize(input_str)

`

**Explanation:

Using Dictionary Grouping

This method groups words based on their sorted character string. It’s more explicit and easier to understand.

**Algorithm

  1. Initialize an empty dictionary anagram_dict.
  2. For each word, sort its characters to create a key.
  3. Add the word to the list corresponding to that key.
  4. The maximum size among all value lists is the answer.

**Code:

Python `

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)

return max(len(val) for val in anagram_dict.values())

words = ['ant', 'magenta', 'magnate', 'tan', 'gnamate'] print(largest_anagram_subset_size(words))

`

**Explanation:

Using lambda + Counter Comparison

This compact one-liner uses a functional programming style. It compares every pair of words using Counter to check if they are anagrams.

Algorithm

  1. For each word x in the list:
  2. Count how many words y are anagrams of x using Counter.
  3. The maximum count found gives the largest subset size.

**Code:

Python `

from collections import Counter

words = ['cars', 'bikes', 'arcs', 'steer'] max_anagrams = max(map(lambda x: sum(Counter(y) == Counter(x) for y in words), words), default=0) print(max_anagrams)

`