Skip to main content

16. Group Anagrams

mediumAsked at Figma

Cluster 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^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters

Examples

Example 1

Input
strs = ["eat","tea","tan","ate","nat","bat"]
Output
[["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2

Input
strs = [""]
Output
[[""]]

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.

Output

Press Run or Cmd+Enter to execute

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 →