20 March 2024
Medium
49. Group Anagrams
Link: https://leetcode.com/problems/group-anagrams
Description: Given an array of strings, group anagrams together.
Solution:
Create object and store sorted string as key and array of strings as value. Iterate over array of strings and for each string, sort it and check this sorted string as key in object. If it is found, push string to array. If it is not found, create new array with string as first element.
var groupAnagrams = function (strs) {
const obj = {}
for (const str of strs) {
const sortedStr = str.split('').sort().join('')
if (obj[sortedStr] !== undefined) {
obj[sortedStr].push(str)
} else {
obj[sortedStr] = [str]
}
}
return Object.values(obj)
}