Group Anagrams in Python

 

 

Program

def group_anagrams(strs):
    """
    Groups anagrams from a list of strings.

    Parameters:
    strs (list): A list of strings to be grouped.

    Returns:
    list: A list of lists, where each sublist contains anagrams.
    """
    from collections import defaultdict
    
    anagrams = defaultdict(list)  # Create a dictionary to hold lists of anagrams
    
    for word in strs:
        # Sort the word to find the anagram key
        key = ''.join(sorted(word))
        anagrams[key].append(word)  # Append the original word to the correct key
    
    return list(anagrams.values())  # Return the grouped anagrams as a list of lists

# Example usage:
if __name__ == "__main__":
    input_strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
    grouped_anagrams = group_anagrams(input_strs)
    print(grouped_anagrams)

Explanation

The program defines a function group_anagrams that takes a list of strings as input and returns a list of lists containing grouped anagrams.

Structure

  • Imports: The program imports defaultdict from the collections module. This allows for easy creation of lists that will hold anagrams keyed by their sorted character strings.
  • Function Definition:
    • def group_anagrams(strs): – This line defines the function.
    • It takes one parameter, strs, which is expected to be a list of strings.
  • Dictionary Creation:
    • anagrams = defaultdict(list) initializes a default dictionary where each value is a list. This will store our grouped anagrams.
  • Loop Through Words:
    • The program iterates over each word in the input list.
    • key = ''.join(sorted(word)) creates a key by sorting the characters in the word and joining them back into a string.
    • anagrams[key].append(word) adds the original word to the list of its corresponding anagram key.
  • Return Statement: return list(anagrams.values()) converts the dictionary values (the grouped anagrams) into a list and returns it.
  • Example Usage: The main block demonstrates how to use the function with a sample list of strings and prints the grouped anagrams.

Conclusion

This program efficiently groups anagrams using sorting and a dictionary. The time complexity is O(NK log K), where N is the number of strings and K is the maximum length of a string.

 

Leave a Reply

Your email address will not be published. Required fields are marked *