Skip to main content

16. Group Anagrams

mediumAsked at Klarna

Group strings that are anagrams of each other.

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

Problem

Given an array of strings strs, group the strings that are anagrams of each other together. You may return the answer in any order.

Constraints

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

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

For each string, check it against every existing group leader via sorted-string compare.

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

Tradeoff:

2. Hash by sorted-key

Sort each string's letters to produce a canonical key, then bucket by that key in a single pass.

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 [...map.values()];
}

Tradeoff:

Klarna-specific tips

Klarna risk teams love this canonicalization pattern because it mirrors how their merchant-settlement engine normalizes vendor names ('Inc.' vs 'INC' vs 'inc') before grouping payouts.

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

Practice these live with InterviewChamp.AI →