Group Anagrams — LeetCode #49 (Medium)
Tags: Array, Hash Table, String, Sorting
Related patterns: Hash Map, Array
Brute Force approach
Time complexity: O(n² * k log k). Space complexity: O(1).
The brute force approach involves checking each string against every other string to see if they are anagrams. This is straightforward but inefficient for larger inputs.
The time complexity is O(n²) because we compare each string with every other string, and sorting each string takes O(k log k), where k is the length of the string.
- Step 1: For each string in the input list, compare it with every other string.
- Step 2: Sort both strings and check if they are equal. If they are, they are anagrams.
- Step 3: Group the anagrams together in a list.
Input: strs = ["eat","tea","tan","ate","nat","bat"]
1. Compare 'eat' with 'tea' → anagram → group = ['tea']
2. Compare 'eat' with 'tan' → not anagram → continue
3. Compare 'eat' with 'ate' → anagram → group = ['tea', 'ate']
4. Compare 'eat' with 'nat' → not anagram → continue
5. Compare 'eat' with 'bat' → not anagram → continue
6. Final group for 'eat' = ['eat', 'tea', 'ate']
Optimal Solution approach
Time complexity: O(n * k log k). Space complexity: 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.
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.
- Step 1: Create a hash map to store groups of anagrams, using the sorted string as the key.
- Step 2: For each string, sort it and use the sorted string as the key to group the original strings.
- Step 3: Collect all groups from the hash map into a list and return it.
Input: strs = ["eat","tea","tan","ate","nat","bat"]
1. 'eat' → key = 'aet' → anagrams = {'aet': ['eat']}
2. 'tea' → key = 'aet' → anagrams = {'aet': ['eat', 'tea']}
3. 'tan' → key = 'ant' → anagrams = {'aet': ['eat', 'tea'], 'ant': ['tan']}
4. 'ate' → key = 'aet' → anagrams = {'aet': ['eat', 'tea', 'ate'], 'ant': ['tan']}
5. 'nat' → key = 'ant' → anagrams = {'aet': ['eat', 'tea', 'ate'], 'ant': ['tan', 'nat']}
6. 'bat' → key = 'abt' → anagrams = {'aet': ['eat', 'tea', 'ate'], 'ant': ['tan', 'nat'], 'abt': ['bat']}
Key Insights
- Anagrams can be identified by sorting their characters.
- Using a hash map allows for efficient grouping of anagrams.
Common Mistakes
- Not considering empty strings or single-character strings.
- Forgetting to handle case sensitivity or character sets beyond lowercase letters.
Interview Tips
- Always clarify the input constraints and edge cases.
- Think about space vs. time trade-offs when choosing data structures.
- Explain your thought process clearly while coding.