← Todas las publicaciones
post9 de abril de 2026
Agrupa Anagramas Juntos
#javascript#strings#map#algorithms
Medium⏱️ Logic Challenge
Write groupAnagrams(words) that groups all anagrams together. ['eat','tea','tan','ate','nat','bat'] → [['eat','tea','ate'],['tan','nat'],['bat']]
Ver solución
function groupAnagrams(words) {
const map = new Map();
for (const word of words) {
const key = [...word].sort().join(''); // sorted letters as key
if (!map.has(key)) map.set(key, []);
map.get(key).push(word);
}
return [...map.values()];
}
groupAnagrams(['eat','tea','tan','ate','nat','bat']);
// [['eat','tea','ate'], ['tan','nat'], ['bat']]
// Insight: anagrams sort to the same string.
// Use that sorted string as a Map key to group them.