15. Group Anagrams
mediumAsked at GlassdoorGlassdoor's review-tagging pipeline buckets free-text snippets by shared character sets — this hash-map grouping problem is their go-to check for candidates who can think beyond brute enumeration when categorizing unstructured text at scale.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings strs, group the anagrams together and return them in any order. Two strings are anagrams of each other if one can be rearranged to form 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: Sorted characters serve as the canonical key: 'eat','tea','ate' all sort to 'aet'.
Example 2
strs = [""][[""]]Approaches
1. Brute force — sort each pair
For every pair of strings, sort both and compare. O(n^2 * k log k) — too slow at 10^4 strings.
- Time
- O(n^2 * k log k)
- Space
- O(nk)
function groupAnagrams(strs) {
const result = [];
const used = new Array(strs.length).fill(false);
for (let i = 0; i < strs.length; i++) {
if (used[i]) continue;
const group = [strs[i]];
const sortedI = strs[i].split('').sort().join('');
for (let j = i + 1; j < strs.length; j++) {
if (!used[j] && strs[j].split('').sort().join('') === sortedI) {
group.push(strs[j]);
used[j] = true;
}
}
result.push(group);
}
return result;
}Tradeoff:
2. Sorted-key hash map
Sort each string's characters to produce a canonical key, then group into a Map. Single O(n * k log k) pass with O(nk) space.
- Time
- O(n * k log k)
- Space
- O(nk)
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:
Glassdoor-specific tips
Glassdoor interviewers care about your instinct when data arrives unordered — much like user reviews. Walk them through why sorted-character keys give you a stable canonical form, and mention that a character-count array key (26 integers) drops the sort to O(nk) if you want to go further. They reward candidates who connect the algorithm to real grouping problems without prompting.
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 Glassdoor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →