Last active
May 23, 2024 20:06
-
-
Save vprasanth/f743af469168d4707ca91987191180ce to your computer and use it in GitHub Desktop.
group-anagram.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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