Skip to main content

15. Group Anagrams

mediumAsked at Mercury

Group strings into buckets where each bucket contains anagrams of each other.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an array of strings, group the anagrams together. Two strings are anagrams when they share the same multiset of characters; output groups in any order.

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • Lowercase English letters

Examples

Example 1

Input
['eat','tea','tan','ate','nat','bat']
Output
[['bat'],['nat','tan'],['ate','eat','tea']]

Example 2

Input
['']
Output
[['']]

Approaches

1. Sort-each as key

Use sorted(string) as a Map key and group entries.

Time
O(n k log k)
Space
O(n k)
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. 26-count signature key

Build a fixed-length signature of character counts as the bucket key — avoids the log factor from sorting.

Time
O(n k)
Space
O(n k)
function groupAnagrams(strs) {
  const m = new Map();
  for (const s of strs) {
    const cnt = new Array(26).fill(0);
    for (const c of s) cnt[c.charCodeAt(0) - 97]++;
    const key = cnt.join('#');
    if (!m.has(key)) m.set(key, []);
    m.get(key).push(s);
  }
  return [...m.values()];
}

Tradeoff:

Mercury-specific tips

Mercury uses signature-bucket grouping for KYC dedup — distinct legal-name spellings that hash to the same normalized form get pulled into one review queue.

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 Mercury interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →