18. Group Anagrams
mediumAsked at CoupangGroup strings that are anagrams of each other, mirroring how Coupang's Korean e-commerce search ranking clusters tokens that normalize to the same canonical form for retrieval.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings strs, group the anagrams together. Return groups 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"][["eat","tea","ate"],["tan","nat"],["bat"]]Example 2
strs=[""][[""]]Approaches
1. Sorted-key bucketing
Sort each string's chars to form a canonical key; group by that key.
- Time
- O(n * k log k)
- Space
- O(n*k)
const m = new Map();
for (const s of strs) {
const k = s.split('').sort().join('');
if (!m.has(k)) m.set(k, []);
m.get(k).push(s);
}
return [...m.values()];Tradeoff:
2. Frequency-tuple bucketing
Build a 26-length count vector per string as the key; avoids sorting.
- Time
- O(n*k)
- Space
- O(n*k)
function groupAnagrams(strs) {
const m = new Map();
for (const s of strs) {
const count = new Array(26).fill(0);
for (const c of s) count[c.charCodeAt(0) - 97]++;
const k = count.join(',');
if (!m.has(k)) m.set(k, []);
m.get(k).push(s);
}
return [...m.values()];
}Tradeoff:
Coupang-specific tips
Coupang's Korean e-commerce search ranking clusters tokens normalized into a canonical form for retrieval; frequency-tuple bucketing scales better than sort-key under their throughput SLO.
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 Coupang interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →