49. Group Anagrams
mediumAsked at OlaGroup strings that are anagrams of each other.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings, group the anagrams together. You can return the answer in any order.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[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. Compare all pairs
For each unseen string, scan the rest for anagrams.
- Time
- O(n^2 * k log k)
- Space
- O(n)
// O(n^2) pairwise sorted-string equality check; omitted for brevityTradeoff:
2. Sorted key bucket
Use each string's sorted characters as a hash map key; values are the groups.
- Time
- O(n * k log k)
- Space
- O(n)
function groupAnagrams(strs) {
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:
Ola-specific tips
Ola tests this as a clean hash-bucket warmup; tie it to clustering address strings that are spelling variants of the same locality.
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 Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →