Anagram Groups By Sorted Key

Group anagrams by their sorted rune key so listen, silent, and enlist share one map entry, with sorted keys keeping printed output deterministic.

GoData Integrity

Code

snippet
package main

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

func anagramKey(word string) string {
	runes := []rune(word)
	sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] })
	return string(runes)
}

func main() {
	words := []string{"listen", "silent", "enlist", "google", "banana"}

	groups := make(map[string][]string)
	for _, w := range words {
		key := anagramKey(w)
		groups[key] = append(groups[key], w)
	}

	sortedKeys := make([]string, 0, len(groups))
	for key := range groups {
		sortedKeys = append(sortedKeys, key)
	}
	sort.Strings(sortedKeys)

	for _, key := range sortedKeys {
		fmt.Printf("%s -> %s\n", key, strings.Join(groups[key], ", "))
	}
}

Anagram Groups By Sorted Key: how the code works

Anagram Groups By Sorted Key comes down to the functions anagramKey and main.

A single loop drives the file — for _, w := range words.

What to watch for

  • Imports stay inside the standard library — nothing to install.

Using it

Signature: func anagramKey(word string) string

Running the file executes main, which drives anagramKey in order.

Key statements

sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] })
for _, key := range sortedKeys {
	fmt.Printf("%s -> %s\n", key, strings.Join(groups[key], ", "))
}
for _, w := range words {
	key := anagramKey(w)
	groups[key] = append(groups[key], w)
}

Interactive Tools for This Topic

FAQ

How do you run Anagram Groups By Sorted Key?
Execute it straight away — the program needs nothing beyond the runtime.