- Interview Questions
- /
- Problems
- /
- Group Anagrams
Group Anagrams
Sort a list of words into groups that are rearrangements of each other. A hash map problem whose real question is what to use as the key. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given an array of lowercase strings strs. Group together the strings that are anagrams of each other, meaning they contain exactly the same letters with the same counts, possibly in a different order.
Return the groups as an array of arrays. Every input string appears in exactly one group, including duplicates. The groups can be in any order, and so can the strings inside each group.
Example 1
- Input
- strs = ["listen", "enlist", "google", "silent", "gogole"]
- Output
- [["listen", "enlist", "silent"], ["google", "gogole"]]
Example 2
- Input
- strs = ["abc"]
- Output
- [["abc"]]
Example 3
- Input
- strs = ["", "b", ""]
- Output
- [["", ""], ["b"]]
The two empty strings are anagrams of each other.
Constraints
- 1 ≤ strs.length ≤ 10⁴
- 0 ≤ strs[i].length ≤ 100
- strs[i] contains only lowercase English letters.
Practice
Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Group Anagrams in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Group Anagrams
Pattern: Hash map keyed by a canonical form
Comparing words pairwise to see whether they're anagrams works, but it's slow and it isn't really what the problem asks. The question is "which bucket does each word belong in?" That calls for a hash map, and the whole problem comes down to choosing a key that is identical for anagrams and different for everything else.
Two keys work:
- The sorted word.
"listen"and"silent"both sort to"eilnst". - The letter counts. A 26-slot count of each letter is the same for every anagram and doesn't require sorting.
Compute the key for each word, append the word to that key's list, and return the lists.
Approach 1: Compare every pair
For each word not yet grouped, scan the rest and pull out every word that is an anagram of it (by comparing sorted forms or letter counts). Simple, but every word may be compared with every other.
Time O(n² · k) · Space O(n · k)
Approach 2: Hash map keyed by the sorted word
Sort the characters of each word and use the result as the map key. Short and readable, and usually the first answer interviewers expect. Sorting costs O(k log k) per word of length k.
Time O(n · k log k) · Space O(n · k)
Approach 3: Hash map keyed by letter counts
For each word, count its letters into a 26-slot array and turn that into a key: a tuple in Python, or a joined string in JavaScript. Append the word to the list for that key, then return all the lists.
When joining counts into a string, put a separator between them. Without one, counts like 1, 11 and 11, 1 both become "111" and unrelated words collide.
Time O(n · k) · Space O(n · k)
| Approach | Time | Space |
|---|---|---|
| Compare every pair | O(n² · k) | O(n · k) |
| Hash map keyed by the sorted word | O(n · k log k) | O(n · k) |
| Hash map keyed by letter counts | O(n · k) | O(n · k) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Group Anagrams solution in Python
def group_anagrams(strs: list[str]) -> list[list[str]]:
groups: dict[tuple[int, ...], list[str]] = {}
for word in strs:
counts = [0] * 26
for ch in word:
counts[ord(ch) - ord("a")] += 1
groups.setdefault(tuple(counts), []).append(word)
return list(groups.values())Group Anagrams solution in JavaScript
function groupAnagrams(strs) {
const groups = new Map();
for (const word of strs) {
const counts = new Array(26).fill(0);
for (let i = 0; i < word.length; i++) counts[word.charCodeAt(i) - 97]++;
const key = counts.join(',');
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(word);
}
return [...groups.values()];
}Common mistakes
- Joining letter counts into a string with no separator, so different count arrays produce the same key.
- Using a set of letters as the key, which treats `"aab"` and `"abb"` as anagrams.
- Dropping duplicate words. Every input string must appear in the output, even repeats.
- Using a mutable list as a dictionary key in Python, which raises `TypeError`. Convert it to a tuple.
What interviewers look for
Frame it as a grouping problem right away: "I'll bucket the words in a hash map; the question is what key to use." Then give the sorted-word key, state its O(k log k) cost, and offer the count key as the linear-time improvement. Interviewers like hearing that you chose the key deliberately.
Mention the separator issue if you build a string key; it shows you've thought about collisions instead of assuming the key is unique.
Follow-up questions
What if the strings can contain any Unicode characters?
A fixed 26-slot array no longer works. Use a sorted copy of the string as the key, or a sorted list of (character, count) pairs from a hash map. Both handle any alphabet.
How would you check whether just two strings are anagrams?
Return false if the lengths differ, then increment counts for one string and decrement for the other. They are anagrams if every count ends at zero. O(k) time, O(1) space for a fixed alphabet.
How would you find every place in a long text where an anagram of a short pattern starts?
Slide a window the length of the pattern across the text, keeping letter counts for the window. Each step adds one letter and removes one, and you compare against the pattern counts (or track how many letters currently match). That is O(n) for a fixed alphabet.
Companies that ask Group Anagrams
Group Anagrams is tagged by 156 companies in our interview dataset. The score shows how often it comes up at each company.
- Ivy Mobility100%
- Abbott100%
- Disney100%
- Avito100%
- Blinkit100%
- Smartsheet100%
- Adobe95.1%
- Yelp94.2%
- Magic Leap94%
- Workday92.1%
- Walmart Labs91.3%
- Trimble90%
- Okta89.2%
- Zoho88.3%
- Cytokinetics88%
- Wissen Technology88%
- Dp World87.6%
- Hashedin87%
- Athenahealth83.9%
- Expedia83.6%
- Airtasker83%
- Square Enix82%
- Envato82%
- Nielsen81.7%
and 132 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required