15. Group Anagrams
mediumAsked at RevolutGroup strings that are anagrams of each other under a canonical key, a Revolut screen that mirrors bucketing different spellings of the same merchant name for ledger reconciliation.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings, group the anagrams together. Return the list of groups in any order; strings within a group may also be in any order.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100Lowercase English letters
Examples
Example 1
strs=["eat","tea","tan","ate","nat","bat"][["eat","tea","ate"],["tan","nat"],["bat"]]Example 2
strs=[""][[""]]Approaches
1. Sorted-string key
Use sorted characters as the bucket key.
- Time
- O(n * k log k)
- Space
- O(n*k)
const m = new Map();
for (const s of strs){ const k = [...s].sort().join(''); if (!m.has(k)) m.set(k,[]); m.get(k).push(s); }
return [...m.values()];Tradeoff:
2. Count-array key
Use a 26-length character-count vector as the key. Linear in total characters.
- Time
- O(n*k)
- Space
- O(n*k)
function groupAnagrams(strs){
const m = new Map();
for (const s of strs){
const cnt = new Array(26).fill(0);
for (const c of s) cnt[c.charCodeAt(0)-97]++;
const k = cnt.join('#');
if (!m.has(k)) m.set(k, []);
m.get(k).push(s);
}
return [...m.values()];
}Tradeoff:
Revolut-specific tips
Revolut frames this as merchant-name canonicalization for transaction enrichment — they expect you to mention case-folding and trimming as a real-world preprocessing step.
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 Revolut interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →