#49
Group Anagrams
MediumArrayHash TableStringSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n² * k log k) | O(n * k log k) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * k log k)Space O(n)
The optimal solution uses a hash table to group anagrams by their sorted string representation. This way, we can efficiently categorize anagrams without comparing each string directly.
⚙️
Algorithm
3 steps- 1Step 1: Create a hash map to store groups of anagrams, using the sorted string as the key.
- 2Step 2: For each string, sort it and use the sorted string as the key to group the original strings.
- 3Step 3: Collect all groups from the hash map into a list and return it.
solution.py8 lines
1from collections import defaultdict
2
3def groupAnagrams(strs):
4 anagrams = defaultdict(list)
5 for s in strs:
6 key = ''.join(sorted(s))
7 anagrams[key].append(s)
8 return list(anagrams.values())ℹ
Complexity note: The time complexity is O(n * k log k) because we sort each string (O(k log k)) and do this for n strings. The space complexity is O(n) for storing the grouped anagrams.
- 1Anagrams can be identified by sorting their characters.
- 2Using a hash map allows for efficient grouping of anagrams.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.