Tutorialspoint
Problem
Solution
Submissions

Group Anagrams from a List of Strings

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a Python function to group anagrams from a list of strings. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. Return a list of lists, where each inner list contains a group of anagrams.

Algorithm for group_anagrams(strs)
  1. Create a dictionary to store anagram groups, where the key uniquely identifies the anagram pattern.
  2. Iterate through each string in the input list.
  3. For each string, generate a key that uniquely identifies its anagram group.
  4. Add the string to the appropriate anagram group in the dictionary.
  5. Return the values of the dictionary as a list of lists.
Example 1
  • Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
  • Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
  • Explanation:
    • - "eat", "tea", and "ate" are anagrams of each other.
    • - "tan" and "nat" are anagrams of each other.
    • - "bat" has no anagrams in the list.
Example 2
  • Input: [""]
  • Output: [[""]]
  • Explanation:
    • - There is only one string in the input, which is the empty string.
    • - The empty string is grouped by itself.
Constraints
  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters
  • Time Complexity: O(n * k) where n is the number of strings and k is the maximum length of a string
  • Space Complexity: O(n * k)
StringsHash MapHCL TechnologiesDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider using a hash table to group anagrams
  • Create a key for each string that uniquely identifies its anagram group
  • One approach is to sort each string to use as the key
  • Another approach is to create a count of characters in each string to use as the key
  • Group strings with the same key together in the hash table

Steps to solve by this approach:

 Step 1: Create an empty dictionary to store anagram groups.
 Step 2: Iterate through each string in the input list.
 Step 3: Sort the characters of the current string to create a unique key for its anagram group.
 Step 4: Add the string to the appropriate anagram group in the dictionary based on its key.
 Step 5: Convert the dictionary values (anagram groups) to a list of lists and return the result.

Submitted Code :