
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)
- Create a dictionary to store anagram groups, where the key uniquely identifies the anagram pattern.
- Iterate through each string in the input list.
- For each string, generate a key that uniquely identifies its anagram group.
- Add the string to the appropriate anagram group in the dictionary.
- 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)
Editorial
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. |
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