49. Group Anagrams
mediumAsked at GoDaddyCluster strings that are anagrams of each other — GoDaddy uses the same sorted-key hash-table pattern to group similar domain name variations and detect typo-squatting slugs in their marketplace.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings strs, group the anagrams together. You may 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 = [""][[""]]Example 3
strs = ["a"][["a"]]Approaches
1. Brute force
Sort each string and use the sorted form as a key; compare every pair.
- Time
- O(n * k * log k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const map = new Map();
for (const str of strs) {
const key = str.split('').sort().join('');
if (!map.has(key)) map.set(key, []);
map.get(key).push(str);
}
return Array.from(map.values());
}Tradeoff:
2. Character-count key
Build a 26-element frequency vector as the hash key; avoids sort and runs in O(k) per string.
- Time
- O(n * k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const map = new Map();
for (const str of strs) {
const count = new Array(26).fill(0);
for (const ch of str) {
count[ch.charCodeAt(0) - 97]++;
}
const key = count.join(',');
if (!map.has(key)) map.set(key, []);
map.get(key).push(str);
}
return Array.from(map.values());
}Tradeoff:
GoDaddy-specific tips
GoDaddy values the character-count key upgrade over the naive sort because their domain-search engine processes millions of slug lookups per minute — shaving from O(k log k) to O(k) per string matters at SMB-hosting scale. State the tradeoff explicitly.
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 GoDaddy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →