Skip to main content

Group Anagrams

LeetCode 49 | Difficulty: Medium​

Medium

Problem 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?

When to use

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.

When to use

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?

When to use

Grouping, finding closest pairs, interval problems, enabling two-pointer or binary search.


Solutions​

Solution 1: C# (Best: 452 ms)​

MetricValue
Runtime452 ms
Memory39.1 MB
Date2020-04-06
Solution
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​

ApproachTimeSpace
Sort + Process$O(n log n)$$O(1) to O(n)$
Hash Map$O(n)$$O(n)$

Interview Tips​

Key Points
  • 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.