49. Group Anagrams
mediumAsked at DuolingoCluster strings that are anagrams of each other into groups — the hash-keying technique Duolingo's vocabulary engine uses to bundle conjugation variants of the same root word into a single learning card set.
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. Two strings are anagrams if one can be formed by rearranging all characters of the other.
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"]]Explanation: All anagrams share the same sorted form as their canonical key.
Example 2
strs = [""][[""]]Example 3
strs = ["a"][["a"]]Approaches
1. Sort-based grouping
For each string, sort its characters to form a canonical key and group strings by that key in a Map.
- Time
- O(n * k log k) where k = max string length
- 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. Optimal — character-count key
Encode each string as a 26-integer frequency tuple; use that string as the Map key, eliminating the sort step.
- Time
- O(n * k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const map = new Map();
const a = 'a'.charCodeAt(0);
for (const s of strs) {
const count = new Array(26).fill(0);
for (const ch of s) count[ch.charCodeAt(0) - a]++;
const key = count.join(',');
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
return [...map.values()];
}Tradeoff:
Duolingo-specific tips
Duolingo's word-grouping systems constantly cluster conjugation forms — 'run', 'ran', 'running' all map to a root. Interviewers expect you to know both the sort key and the frequency-count key approaches and to articulate when each wins: sort is simpler and O(k log k); count key is O(k) but produces a longer key string. A common follow-up is 'How would you handle Unicode characters or multi-character grapheme clusters?' — answer: use a Map with custom hash or normalize to code points before counting.
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 Duolingo interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →