16. Group Anagrams
mediumAsked at KlarnaGroup 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^40 <= strs[i].length <= 100
Examples
Example 1
strs = ["eat","tea","tan","ate","nat","bat"][["bat"],["nat","tan"],["ate","eat","tea"]]Example 2
strs = [""][[""]]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.
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 →