18. Group Anagrams
mediumAsked at WiseBucket strings by anagram class — Wise treats this as the canonical hash-keyed bucketing problem behind their FX matching engine.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings, group the anagrams together. You may return the answer in any order, but each group must contain all and only the strings that share an anagram class.
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'][['eat','tea','ate'],['tan','nat'],['bat']]Example 2
strs=[''][['']]Approaches
1. Pairwise anagram check
For each string, scan existing groups for one whose head is an anagram; otherwise start a new group.
- Time
- O(n^2 * k log k)
- Space
- O(n*k)
const groups=[];
const key=s=>s.split('').sort().join('');
for (const s of strs){
const g=groups.find(g=>key(g[0])===key(s));
if (g) g.push(s); else groups.push([s]);
}
return groups;Tradeoff:
2. Sorted-key hash map
Sort each string's characters to form a canonical key, then bucket by key in a Map. One pass.
- Time
- O(n * k log k)
- Space
- O(n*k)
function groupAnagrams(strs){
const buckets = new Map();
for (const s of strs){
const key = s.split('').sort().join('');
if (!buckets.has(key)) buckets.set(key, []);
buckets.get(key).push(s);
}
return [...buckets.values()];
}Tradeoff:
Wise-specific tips
Wise wants the canonical-key bucketing pattern because their FX matching engine groups orders by symmetric currency keys in exactly this shape.
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 Wise interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →