Skip to content

Instantly share code, notes, and snippets.

@vprasanth
Last active May 23, 2024 20:06
Show Gist options
  • Save vprasanth/f743af469168d4707ca91987191180ce to your computer and use it in GitHub Desktop.
Save vprasanth/f743af469168d4707ca91987191180ce to your computer and use it in GitHub Desktop.
group-anagram.ts
// https://leetcode.com/problems/group-anagrams/description/
function groupAnagrams(strs: string[]): string[][] {
if (!strs) return [[]];
if (strs.length === 1) return [strs];
const sorted = strs.map(word => {
return word.split("").sort().join("");
});
const realMap = new Map();
for (let i = 0; i < sorted.length; i++) {
let key = sorted[i];
let value = strs[i];
if (realMap.has(key)) {
realMap.set(key, [...realMap.get(key), value]);
} else {
realMap.set(key, [value]);
}
}
const result = [];
realMap.forEach((value, key) => {
result.push(value);
});
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment