Skip to main content

12. Group Anagrams

mediumAsked at Autodesk

Group an array of strings such that anagrams end up in the same bucket.

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, using all the original letters exactly once.

Constraints

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

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. Pairwise compare

Walk pairs and merge if sorted forms match.

Time
O(n^2 * k log k)
Space
O(nk)
for each pair (i,j): if sorted(s[i])===sorted(s[j]) union them.

Tradeoff:

2. Hash by sorted key

Each anagram class shares the same sorted string. Map each input to its sorted key and append to that bucket.

Time
O(n * k log k)
Space
O(nk)
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 Array.from(map.values());
}

Tradeoff:

Autodesk-specific tips

Bucketing by canonical key is what Autodesk does to deduplicate symmetric-equivalent geometry signatures inside Fusion 360 indexing.

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

Practice these live with InterviewChamp.AI →