Python
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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)