26. Group Anagrams
mediumAsked at EtsyCluster strings that are anagrams of each other — Etsy uses this hash-key normalization pattern to deduplicate misspelled listing tags ('handmade', 'hnadmade') before indexing.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[i] consists of lowercase English letters
Examples
Example 1
strs = ["eat","tea","tan","ate","nat","bat"][["bat"],["nat","tan"],["ate","eat","tea"]]Example 2
strs = [""][[""]]Approaches
1. Sort each word as key
Sort the characters of each word alphabetically to produce a canonical key. Group words by key using a Map. Two anagrams produce the same sorted key. O(n * k log k) where k is the max word length.
- Time
- O(n * k log k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const map = new Map();
for (const s of strs) {
const key = s.split('').sort().join('');
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
return [...map.values()];
}Tradeoff:
2. Frequency count as key
Instead of sorting, build a 26-length frequency array for each word and stringify it as the key (e.g., '1,0,0,...,1,...'). Avoids the sort's log factor — O(n * k) overall.
- Time
- O(n * k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const map = new Map();
for (const s of strs) {
const freq = new Array(26).fill(0);
for (const ch of s) freq[ch.charCodeAt(0) - 97]++;
const key = freq.join(',');
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
return [...map.values()];
}Tradeoff:
Etsy-specific tips
Etsy uses anagram grouping for tag normalization and search synonym expansion. Interviewers appreciate when you articulate the key insight: 'two strings are anagrams if and only if their sorted forms are identical' — then pivot to the frequency approach to show you can eliminate the sort. Mention that the frequency key approach is more general and extends to Unicode if you replace the 26-slot array with a Map.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Group Anagrams and other Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →