Skip to main content

49. Group Anagrams

mediumAsked at Airbnb

Cluster words that are rearrangements of each other — Airbnb's search team applies this hash-map grouping pattern to deduplicate listing titles that differ only in word order, surfacing canonical results to guests.

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

Problem

Given an array of strings strs, group all anagrams together and return them as a list of groups. The answer can be returned in any order.

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"]]

Explanation: Words in each group are anagrams of each other.

Example 2

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

Approaches

1. Sort-based key

Sort each string's characters to produce a canonical key. Group strings with the same key using a hash map.

Time
O(n * k log k)
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-count key

Build a 26-length frequency array for each word and use it as a hash map key. Avoids the sort step, reducing per-word cost from O(k log k) to O(k).

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:

Airbnb-specific tips

Airbnb interviewers often reframe this as: 'How would you group listing descriptions that are the same content but word order varies?' The character-count key is the preferred answer — explain that for long strings, avoiding a sort is meaningful. Be prepared for a follow-up about hash collisions with the count-based key, and why it is still safe for fixed lowercase alphabets.

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

Practice these live with InterviewChamp.AI →