Given a list of words, group them into sets where each set contains words that are anagrams of each other.
💡 Model Answer
An anagram group contains words that consist of the same letters in any order. A straightforward solution is to use a hash map where the key is a canonical representation of the word, such as its letters sorted alphabetically. For each word, sort its characters, use that string as the key, and push the original word into the array stored at that key.
function groupAnagrams(words) {
const map = new Map();
for (const w of words) {
const key = w.split('').sort().join('');
if (!map.has(key)) map.set(key, []);
map.get(key).push(w);
}
return Array.from(map.values());
}This algorithm runs in O(n·k log k) time, where n is the number of words and k is the average word length (due to sorting). Space complexity is O(n·k) for storing the groups. For very long words, a counting sort (26‑letter frequency array) can reduce the per‑word cost to O(k). The resulting array of arrays contains each anagram group.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500