Skip to main content

26. Group Anagrams

mediumAsked at Dropbox

Cluster strings that are anagrams of each other into groups — Dropbox applies content-addressable hashing for the same reason: two files with identical byte-frequency fingerprints are dedup candidates regardless of filename.

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

Problem

Given an array of strings strs, group the anagrams together. You can return the answer in any order. An anagram is a word formed by rearranging the letters of another word using each letter exactly once.

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. Sort each word as key

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

Time
O(n * k log k) where k = max string length
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. Frequency array as key

Build a 26-element frequency count for each string and use that as a hash key. Avoids sorting — O(k) per string instead of O(k log k).

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

Tradeoff:

Dropbox-specific tips

Dropbox interviewers often extend this to: 'Given millions of files, group duplicates by content without reading each file twice.' The frequency-key pattern generalizes to content-addressable storage — mention that replacing sort-based keys with a rolling hash would let you handle byte streams too, which connects directly to Dropbox's block-level dedup architecture.

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

Practice these live with InterviewChamp.AI →