16. Group Anagrams
mediumAsked at FigmaCluster a list of strings so that every group contains the same multiset of characters. Figma uses this as a warm-up before scene-graph hash-bucketing questions.
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. An anagram is a word formed by rearranging the letters of another.
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 = [""][[""]]Approaches
1. Sorted-string key
Sort each string and bucket by the canonical sorted form.
- Time
- O(n * k log k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const m = new Map();
for (const s of strs) {
const k = [...s].sort().join('');
if (!m.has(k)) m.set(k, []);
m.get(k).push(s);
}
return [...m.values()];
}Tradeoff:
2. Character-count key
Use a 26-length frequency vector serialized to a string as the bucket key. Avoids the per-string sort cost and scales linearly in total characters — closer to how a scene graph would bucket identical node signatures.
- Time
- O(n * k)
- Space
- O(n * k)
function groupAnagrams(strs) {
const m = new Map();
for (const s of strs) {
const counts = new Array(26).fill(0);
for (const ch of s) counts[ch.charCodeAt(0) - 97]++;
const key = counts.join('#');
if (!m.has(key)) m.set(key, []);
m.get(key).push(s);
}
return [...m.values()];
}Tradeoff:
Figma-specific tips
Figma rewards candidates who explicitly draw the parallel between anagram-bucketing and node-signature bucketing in a scene graph — bring up the connection.
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 Figma interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →