19. Group Anagrams
mediumAsked at YelpGroup an array of strings by anagram class — Yelp uses this canonicalization pattern to test whether candidates can bucket reviews by stable signature for fraud clustering.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings strs, group the anagrams together. Return the answer in any order; an anagram is 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. Pairwise compare
Test every string against every existing group's representative.
- Time
- O(n^2 * k log k)
- Space
- O(nk)
const groups = [];
for (const s of strs) {
const sorted = s.split('').sort().join('');
const hit = groups.find(g => g.key === sorted);
if (hit) hit.items.push(s);
else groups.push({ key: sorted, items: [s] });
}
return groups.map(g => g.items);Tradeoff:
2. Hash by sorted-key
Each anagram class has the same sorted-character signature; bucket strings by that key in one pass.
- Time
- O(n * k log k)
- Space
- O(nk)
function groupAnagrams(strs) {
const map = new Map();
for (const s of strs) {
const k = s.split('').sort().join('');
if (!map.has(k)) map.set(k, []);
map.get(k).push(s);
}
return [...map.values()];
}Tradeoff:
Yelp-specific tips
Yelp interviewers will pivot to review fraud — be ready to discuss how sorted-key bucketing extends to clustering review payloads that share word multisets despite shuffled phrasing.
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 Yelp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →