Group Anagrams

View on LeetCode

Question

You're given a list of strings. Group them together so that each group contains words that are anagrams of each other.

An anagram means the same letters in a different order. Return the grouped results as a list of string arrays.

Example

Input: ["eat", "tea", "tan", "ate", "nat", "bat"]

Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]

Explanation: Each group contains words made from the same letters.


Input: [""]

Output: [[""]]


Input: ["a"]

Output: [["a"]]

My Notes

Visual

Input Words: eat tea tan ate nat bat ["eat", "tea", "ate"] ["tan", "nat"] ["bat"]

package main

import (
    "fmt"
    "sort"
    "strings"
)

func main() {
    result := groupAnagrams([]string{"eat", "tea", "tan", "ate", "nat", "bat"})
    fmt.Println(result)
}

func groupAnagrams(strs []string) [][]string {
    lookup := make(map[string][]string)

    for _, item := range strs {
        arr := strings.Split(item, "")
        sort.Strings(arr)
        key := strings.Join(arr, "")
        lookup[key] = append(lookup[key], item)
    }

    ans := [][]string{}
    for _, value := range lookup {
        ans = append(ans, value)
    }
    return ans
}