Leetcode Practice

LC 49. Group Anagrams

Last updated
Reading time
1 min read

The problem

Solution - O(n)O(n) Time

For this problem, I use the same technique to sort the letters alphabetically as in this problem. Then, I store the sorted string as the key in a map where the values collect any string that, when sorted, is found to be an anagram. Once I've grouped all the anagrams in the map, I can iterate out each array from the map and return this. In fact, I chose the Map type to make that slightly easier, but using a plain object will work too.

function groupAnagrams(strs: string[]): string[][] {
  let map = new Map()
  for (let i = 0; i < strs.length; i++) {
    let sortedStr = strs[i].split('').sort().join('')
    if (map.has(sortedStr)) {
      map.get(sortedStr).push(strs[i])
    } else {
      map.set(sortedStr, [strs[i]])
    }
  }

  return [...map.values()]
}