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.

%0 node_1687105677322 o node_1687105782181 1 node_1687105677322->node_1687105782181 node_1687105507380 l node_1687105554318 2 node_1687105507380->node_1687105554318 node_2 e node_1687105486243 1 node_2->node_1687105486243 node_1 H node_1_1 1 node_1->node_1_1 node_0 Character node_0_1 Count node_0->node_0_1
Example of counting character frequency in the string "Hello"
svg viewer

Code

package main
import (
"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 string
fmt.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 78: The countCharacters function is defined, taking a string str as input and returning a map of type map[rune]int. Since Go does not have a specific data type for characters, it uses the rune type to represent character values. The function initializes an empty map named frequency to store the frequencies of each character.

  • Lines 914: The for loop iterates over each character (char) in the str string. Inside the loop, the code increments the count of char in the frequency map by one.The frequency map is returned once the loop is complete.

  • Lines 21–23: The for loop iterates over the frequency map using range. 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 O(n)O(n), where nn is the length of the input string. Inside the loop, the access of a map has a time complexity of O(1)O(1)

Therefore, the overall time complexity of the countCharacters function is O(n)O(n) because it performs a linear iteration over the input string.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved