20. Group Anagrams
mediumAsked at NotionBucket strings by their sorted-character signature — the same hash-map grouping Notion uses to cluster tags, block types, and database property values without scanning every entry on every lookup.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings, group the anagrams together and return each group as a list. The order of groups and words within groups does not matter.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[i] consists of lowercase English letters only
Examples
Example 1
strs = ["eat","tea","tan","ate","nat","bat"][["bat"],["nat","tan"],["ate","eat","tea"]]Example 2
strs = [""][[""]]Approaches
1. Sort each string as key
Sort the characters of each word to produce a canonical key; group words by key in a hash 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. Character frequency array as key
Build a 26-element frequency count per word; serialize it as a string key — avoids the k log k sort cost, useful when strings are long.
- Time
- O(n * k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const map = 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 key = count.join(',');
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
return [...map.values()];
}Tradeoff:
Notion-specific tips
Notion's block search and database grouping both hinge on fast canonical-key construction. They want you to compare the sort-based key vs. frequency-array key approaches and justify the choice based on string length. Also note that frequency arrays generalize to Unicode — mention it if time allows.
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 Notion interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →