20. Group Anagrams
mediumAsked at SquareCluster merchant names that are anagrams of each other so Square's compliance team can batch-review aliases — a hash-map keyed on sorted character signatures groups thousands of merchant strings in a single linear pass.
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.
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 string as key
Sort the characters of each word to produce a canonical key; use a map from key to list of words. Simple, works, but sorting each word is O(k log k).
- 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].sort().join('');
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
return [...map.values()];
}Tradeoff:
2. Frequency count as key
Build a 26-integer count array for each word and stringify it as the map key. Avoids sorting — O(n * k) overall, better when words are long.
- Time
- O(n * k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const map = new Map();
for (const s of strs) {
const count = new Array(26).fill(0);
const a = 'a'.charCodeAt(0);
for (const c of s) count[c.charCodeAt(0) - a]++;
const key = count.join(',');
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
return [...map.values()];
}Tradeoff:
Square-specific tips
Square sees two variants: which grouping strategy you pick, and whether you can articulate the tradeoff between sort-key vs count-key under different input shapes. Mention that sort-key is simpler to read in a code review while count-key wins when average word length k is large. Readable code that ships wins over micro-optimized code that sits in review.
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 Square interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →