15. Group Anagrams
mediumAsked at ByteDanceCluster anagrams into groups — ByteDance uses it to test hashable-canonical-form thinking before scaling to comment-clustering pipelines.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings strs, group the anagrams together and return the groups in any order. Two strings are anagrams if one is a rearrangement 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"][["eat","tea","ate"],["tan","nat"],["bat"]]Example 2
strs = [""][[""]]Approaches
1. Pairwise anagram check
Compare every pair with character-count equality.
- Time
- O(n^2 * k)
- Space
- O(n)
// for each unassigned string, scan the rest for anagramsTradeoff:
2. Sorted-key bucket
Use the sorted character sequence as a hash key and bucket each string into a Map<string, string[]>.
- 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:
ByteDance-specific tips
ByteDance values a quick discussion of trading the sort key for a 26-count tuple key — the same canonical-form trick their moderation team uses to cluster near-identical comments.
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 ByteDance interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →