Skip to main content

12. Group Anagrams

mediumAsked at Postman

Group strings into lists where each list contains anagrams of each other.

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

Problem

Given an array of strings, group the anagrams together. Return the answer in any order; the groups themselves can be 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"]]

Example 2

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

Approaches

1. Sort key

Use the sorted string as a hash map key; group originals under that key.

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

Tradeoff:

2. Frequency-tuple key

Bucket each string by its 26-element char count serialized as the key, avoiding the sort.

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

Tradeoff:

Postman-specific tips

Postman engineers think in terms of canonical-key bucketing because grouping equivalent requests (same path + sorted query keys) is exactly how the proxy collapses duplicates.

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

Practice these live with InterviewChamp.AI →