Skip to main content

15. Group Anagrams

mediumAsked at Freshworks

Bucket strings by anagram equivalence — Freshworks uses this shape for grouping tickets by canonical tag combinations regardless of label order.

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

Problem

Given an array of strings strs, group the anagrams together. Two strings are anagrams if they contain the same characters with the same counts.

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
[["eat","tea","ate"],["tan","nat"],["bat"]]

Example 2

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

Approaches

1. Brute force (pairwise compare)

For each string, compare against existing group reps via sorted-string equality. O(n^2 * k log k).

Time
O(n^2 * k log k)
Space
O(n*k)
const groups = [];
for (const s of strs) {
  const key = [...s].sort().join('');
  let found = false;
  for (const g of groups) if ([...g[0]].sort().join('') === key) { g.push(s); found = true; break; }
  if (!found) groups.push([s]);
}
return groups;

Tradeoff:

2. Hash by sorted-letter key

Sort each string's characters to produce its canonical anagram key. Group into a Map keyed by that string. Return Map values.

Time
O(n * k log k)
Space
O(n*k)
function groupAnagrams(strs) {
  const m = new Map();
  for (const s of strs) {
    const key = [...s].sort().join('');
    if (!m.has(key)) m.set(key, []);
    m.get(key).push(s);
  }
  return [...m.values()];
}

Tradeoff:

Freshworks-specific tips

Freshworks will ask if there's a faster key than sorting — mention the 26-length character-count tuple as an O(k) alternative and explain when each wins.

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

Practice these live with InterviewChamp.AI →