Go Program to Group Anagrams

 

Program Code


package main

import (
    "fmt"
    "sort"
)

// groupAnagrams takes a slice of strings and groups anagrams together.
func groupAnagrams(strs []string) [][]string {
    // Create a map to hold the grouped anagrams
    anagrams := make(map[string][]string)

    // Iterate through each string in the input slice
    for _, str := range strs {
        // Convert the string to a slice of runes
        runes := []rune(str)
        // Sort the runes
        sort.Slice(runes, func(i, j int) bool {
            return runes[i] < runes[j]
        })
        // Convert sorted runes back to a string
        sortedStr := string(runes)

        // Group the original string in the map using the sorted string as the key
        anagrams[sortedStr] = append(anagrams[sortedStr], str)
    }

    // Prepare the result by converting the map values to a slice of slices
    result := make([][]string, 0, len(anagrams))
    for _, group := range anagrams {
        result = append(result, group)
    }

    return result
}

func main() {
    // Example usage
    strs := []string{"eat", "tea", "tan", "ate", "nat", "bat"}
    groupedAnagrams := groupAnagrams(strs)
    fmt.Println(groupedAnagrams)
}
    

Program Explanation

This program defines a function groupAnagrams that takes a slice of strings and returns a 2D slice containing grouped anagrams.

Program Structure

  • Imports: The program imports the fmt package for output and the sort package to sort strings.
  • groupAnagrams function:
    • It creates a map called anagrams to store lists of anagrams keyed by their sorted character representation.
    • For each string in the input, it converts the string to a slice of runes, sorts them, and constructs a new sorted string.
    • It appends the original string to the appropriate slice in the map.
  • Converting map to slice: The map values (anagram groups) are then collected into a 2D slice called result.
  • main function: The main function demonstrates the use of groupAnagrams with a sample input and prints the result.

Documentation

The groupAnagrams function is the core of the program:

  • Parameters:
    strs []string – A slice of strings that may contain anagrams.
  • Returns:
    [][]string – A 2D slice where each inner slice contains a group of anagrams.
  • Complexity: The time complexity is O(n * k log k), where n is the number of strings and k is the maximum length of a string. This is due to sorting each string.

Example Output

If you run the program with the provided input, you may see output similar to:

[ [eat tea ate] [tan nat] [bat] ]

 

Leave a Reply

Your email address will not be published. Required fields are marked *