Created
November 9, 2024 07:20
-
-
Save sAVItar02/6613b4b570514b5837935cfb5e6c6649 to your computer and use it in GitHub Desktop.
Group Anagrams
This file contains 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
/** | |
* @param {string[]} strs | |
* @return {string[][]} | |
*/ | |
var groupAnagrams = function(strs) { | |
let map = {}; | |
let res = []; | |
for(let i=0; i<strs.length; i++) { | |
let temp = strs[i].split(""); | |
temp.sort(); | |
temp = temp.join(''); | |
if(map[temp]) map[temp].push(strs[i]); | |
else { | |
map[temp] = [strs[i]]; | |
} | |
} | |
Object.keys(map).forEach(key => { | |
res.push(map[key]); | |
}) | |
return res; | |
}; | |
// Sort the characters of the string and store it as a key in a map | |
// For every string where the sorted alphabets match a key in the map, store it in the array | |
// If no match, then create a new key and store it in an array | |
// Return the values in the map as an array | |
// Time: O(n * m * log(m)) | |
// Space: O(n * m) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment