9. Group Anagrams
mediumAsked at AdyenGroup strings that are anagrams of each other into the same bucket.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings, group the anagrams together. Return the answer in any order.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100Lowercase 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 grouping
Group by sorted-character string.
- Time
- O(n * k log k)
- Space
- O(n * k)
const map = new Map();
for (const s of strs) {
const key = [...s].sort().join('');
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
return [...map.values()];Tradeoff:
2. Count-vector key
Hash a 26-length frequency array as the bucket key.
- Time
- O(n * k)
- Space
- O(n * k)
function groupAnagrams(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 key = c.join(',');
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
return [...map.values()];
}Tradeoff:
Adyen-specific tips
Adyen rewards hashing a count vector over sorting since their fraud-signal pipelines bucket transaction fingerprints under similar O(k) constraints.
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 Adyen interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →