Group Anagrams

Problem statement

Cluster the input strings so that words made from the same letters land in the same group. Order of groups (and words inside a group) does not matter.

Example:

Input:

["abc", "bcd", "bca", "dcb"]

Expected output (grouping only):

[["abc", "bca"], ["bcd", "dcb"]]

Practice on LeetCode: Group Anagrams

Golang Solution

import (
    "sort"
)

func groupAnagrams(strs []string) [][]string {

    hashMap := make(map[string][]string)
    result := make([][]string, 0)
    
    for _, str := range strs {
        sorted := sortString(str)
        if res, ok := hashMap[sorted]; ok {
            hashMap[sorted] = append(res, str)
        } else {
            hashMap[sorted] = []string{str}
        }
    }

    for _, res := range hashMap {
        result = append(result, res)
    }

    return result
}

func sortString(s string) string {
    runes := []rune(s)

    sort.Slice(runes, func(i, j int) bool {
        return runes[i] < runes[j]
    }) 

    return string(runes)
}