How to count character frequency in Go
We can determine the frequency of unique characters in a given string using the map data structure provided by Go. A map is a collection of (key: value) pairs, where in this case, each unique character in the string serves as a key. The corresponding value represents the count of occurrences for that character. The make function is used to construct an array or map.
Let's consider an example where we input the string "Hello". In this case, we would expect the following results.
Code
package mainimport ("fmt")func countCharacters(str string) map[rune]int {frequency := make(map[rune]int)for _, char := range str {frequency[char] = frequency[char]+1}return frequency}func main() {var input stringfmt.Scanln(&input)frequency := countCharacters(input)fmt.Println("Character frequency:")for char, count := range frequency {fmt.Printf("%c: %d\n", char, count)}}
Enter the input below
Explanation
Lines 7–8: The
countCharactersfunction is defined, taking a stringstras input and returning a map of typemap[rune]int. Since Go does not have a specific data type for characters, it uses therunetype to represent character values. The function initializes an empty map namedfrequencyto store the frequencies of each character.Lines 9–14: The
forloop iterates over each character (char) in thestrstring. Inside the loop, the code increments the count ofcharin thefrequencymap by one.Thefrequencymap is returned once the loop is complete.Lines 21–23: The
forloop iterates over thefrequencymap usingrange. In each iteration, it retrieves the character (char) and its corresponding frequency (count).
Time complexity
The time complexity depends on the length of the input string, denoted as n. The countCharacters function iterates over each character in the input string str using a for loop. This loop has a complexity of
Therefore, the overall time complexity of the countCharacters function is
Free Resources