Group Anagrams
LeetCode 49 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
- There is no string in strs that can be rearranged to form `"bat"`.
- The strings `"nat"` and `"tan"` are anagrams as they can be rearranged to form each other.
- The strings `"ate"`, `"eat"`, and `"tea"` are anagrams as they can be rearranged to form each other.
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
- `1 <= strs.length <= 10^4`
- `0 <= strs[i].length <= 100`
- `strs[i]` consists of lowercase English letters.
Topics: Array, Hash Table, String, Sorting
Approachβ
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
Need fast lookups, counting frequencies, finding complements/pairs.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Sortingβ
Sort the input to bring related elements together or enable binary search. Consider: does sorting preserve the answer? What property does sorting give us?
Grouping, finding closest pairs, interval problems, enabling two-pointer or binary search.
Solutionsβ
Solution 1: C# (Best: 452 ms)β
| Metric | Value |
|---|---|
| Runtime | 452 ms |
| Memory | 39.1 MB |
| Date | 2020-04-06 |
public class Solution {
public IList<IList<string>> GroupAnagrams(string[] strs) {
Dictionary<string, List<string>> ana = new Dictionary<string, List<string>>();
foreach (var anagram in strs)
{
var anagramArray = anagram.ToCharArray();
Array.Sort(anagramArray);
var sorted = new String(anagramArray);
if(ana.ContainsKey(sorted))
{
ana[sorted].Add(anagram);
}
else
{
ana.Add(sorted, new List<string>{anagram});
}
}
IList<IList<string>> anagrams = ana.Select(x=>(IList<string>)(x.Value)).ToList();
return anagrams;
}
}
π 1 more C# submission(s)
Submission (2018-01-16) β 624 ms, N/Aβ
public class Solution {
public IList<IList<string>> GroupAnagrams(string[] strs) {
Dictionary<string, List<string>> ana = new Dictionary<string, List<string>>();
foreach (var anagram in strs)
{
var anagramArray = anagram.ToCharArray();
Array.Sort(anagramArray);
var sorted = new String(anagramArray);
if(ana.ContainsKey(sorted))
{
ana[sorted].Add(anagram);
}
else
{
ana.Add(sorted, new List<string>{anagram});
}
}
IList<IList<string>> anagrams = ana.Select(x=>(IList<string>)(x.Value)).ToList();
return anagrams;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Sort + Process | $O(n log n)$ | $O(1) to O(n)$ |
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Hash map gives O(1) lookup β think about what to use as key vs value.