Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to convert a slice of strings and group all the anagrams into subslices in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "sort"
)

// groupAnagrams groups an array of strings into subarrays of anagrams.
func groupAnagrams(words []string) [][]string {
    anagramMap := make(map[string][]string)

    for _, word := range words {
        // Sort the characters in the word to create a key
        sorted := sortString(word)

        // Append the word to the group identified by the sorted key
        anagramMap[sorted] = append(anagramMap[sorted], word)
    }

    // Collect the grouped anagrams into a slice of slices
    result := make([][]string, 0, len(anagramMap))
    for _, group := range anagramMap {
        result = append(result, group)
    }

    return result
}

// sortString returns a string with its characters sorted alphabetically
func sortString(s string) string {
    runes := []rune(s)
    
    sort.Slice(runes, func(i, j int) bool {
        return runes[i] < runes[j]
    })
    
    return string(runes)
}

func main() {
    words := []string{"eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"}
    result := groupAnagrams(words)

    fmt.Println("Grouped anagrams:")
    for _, group := range result {
        fmt.Println(group)
    }
}



/*
run:

Grouped anagrams:
[eat tea ate]
[rop orp pro]
[nat tan]
[bat]

*/

 



answered Nov 15, 2025 by avibootz
...