Golang Program to Find the Frequency of Each Element in an Array
Last Updated :
23 Jul, 2025
Given an array of some particular data type, we want to find the frequency(number of occurrences) of the elements in the array. We can do that with the help of maps in Golang. By creating a specific datatype map with integer we can iterate over the given array and add the count to the key as the frequency of that element in the array.
Integer Array
Let's say we have a defined integer array of n elements, we simply want to map the elements with their frequency in the array using a map. Firstly, we will define an array, it can be generated or inputted from the user depending on the program's usage. Here we will manually populate the array just for understanding the implementation. After we have an array of integers we can create a map that maps an integer to an integer as we have an integer array, the keys in the map would be elements of the array and the value as the frequency/count of the element.
freq := make(map[int]int)
We can use make for creating a map. Simply write the key type and the value type for the map you want to create.
After creating an empty map we can iterate over the integer array and set its key as the frequency. By default, the frequency of the first time occurring key is set as zero so we can increment it by one the first time we visit an element in the array.
for _ , num := range arr {
freq[num] = freq[num]+1
}
The blank identifier (_) is simply the index of the array and num is the element at that index, so we can iterate over the range in the array i.e. the number of elements in the array. We use the num as the key which is the element in the array and map[num] as the value to the key num. Thus we increment the value by one for each unique element as a key.
Below is the complete program.
Go
// Go program to find the frequency of an integer array
package main
import "fmt"
func main(){
arr := []int{90, 70, 30, 30, 10, 80, 40, 50, 40, 30}
freq := make(map[int]int)
for _ , num := range arr {
freq[num] = freq[num]+1
}
fmt.Println("Frequency of the Array is : ", freq)
}
Output:
Frequency of the array is: map[10:1 30:3 40:2 50:1 70:1 80:1 90:1]
So, as we can see the frequency map was created that maps the elements in the array to their frequency of occurring.
Converting into a Function
We can even convert the logic to a function for creating a frequency map for a given array of integers. We simply need to parse the array as a parameter and the return type as a map of an integer with the integer as a function head. The logic remains the same for creating a frequency map and populating it with keys and values with elements and their frequencies.
Go
// Go program to convert logic into function
package main
import "fmt"
func main(){
arr := []int{90, 70, 30, 30, 10, 80, 40, 50, 40, 30}
freq_map := frequency_map(arr)
fmt.Println("Frequency of the Array is : ", freq_map)
}
func frequency_map( arr []int) map[int]int{
freq := make(map[int]int)
for _ , num := range arr {
freq[num] = freq[num]+1
}
return freq
}
Output:
Frequency of Array is : map [10:1 30:3 40:2 50:1 70:1 80:1 90:1]
Thus, we were able to create a frequency map for an integer array using a map in Go lang.
String
Let's say we have a string and we want to create a frequency count for each character in the string. In this case, we will create a map of string to an integer, we will store each character in the string as a string because it is convenient to display the content and store the count of that string character as the value in the map.
Note: We can even use rune or byte type in place of a string key, the problem with that is it displays the Unicode/ASCII code as the key and not the string itself.
Firstly we will define a string. Similar to the integer map we will create a map that maps a string to an integer like so:
freq := make(map[string]int)
After creating a map, we simply iterate over the string character by character and increment the value of the key, here the key is the character of the string. We will concatenate the character (byte/rune) type as a string just because it is convenient to read the map as a human. But you can keep it as it is then you might have to change the key type of the map to:
freq := make(map[byte]int) OR freq := make(map[rune]int)
This will create a map that stores the keys as Unicode values of the character in the string.
We then iterate over the string and increment the value of the character key in the string as follows:
for _ , char := range word {
freq[string(char)] = freq[(char)]+1
}
So, finally combining the pieces, we have a script that takes in a string and maps each character(string type) as the key and its frequency in the string as its value in the map.
Go
// Go program to that takes string and map each character
package main
import "fmt"
func main(){
arr := "geeksforgeeks"
freq := make(map[string]int)
for _ , char := range arr {
freq[string(char)] = freq[string(char)]+1
}
fmt.Println("Frequency of Array is : ", freq)
}
Output:
Frequency of Array is : map[e:4 f:1 g:2 k:2 0:1 r:1 s:2]
Thus, we can see we get the map of each unique character in the given string with its frequency or count of its occurrence in the entire string.
Using rune/byte as keys in the map
Also if we use the rune/byte data type to create the map without concatenating the character to a string, we will get the output as below:
Go
// Go program using rune/byte as keys in the map
package main
import "fmt"
func main(){
arr := "geeksforgeeks"
freq := make(map[rune]int)
for _ , char := range arr {
freq[char] = freq[char]+1
}
fmt.Println("Frequency of Array is : ", freq)
}
Output:
Frequency of Array is : map[101:4 102:1 103:2 107:2 111:1 114:1 115:2]
The same is the output for byte except it won't accept the characters which are not in ASCII (0 to 255) codes and hence quite limited in the sets of characters. The byte would give a compilation error if the value is out of bounds from its range for a byte. The default value selected if not specified for a character is a rune in Go lang. Still, if you want to use byte as a key in the map, you can specify it in the declaration just as a rune and therefore you also need to concatenate it with a byte.
Go
package main
import "fmt"
func main(){
arr := "geeksforgeeks"
freq := make(map[byte]int)
for _ , char := range arr {
freq[byte(char)] = freq[byte(char)]+1
}
fmt.Println("Frequency of Array is : ", freq)
}
Output:
Frequency of Array is : map[101:4 102:1 103:2 107:2 111:1 114:1 115:2]
Converting to a function
Also, here we can convert the procedural code into a functional approach by creating a function for creating the frequency count of the characters in the string.
Go
// Go program to converting into function
package main
import "fmt"
func main(){
arr := "geeksforgeeks"
freq_map := frequency_map(arr)
fmt.Println("Frequency of Array is : ", freq_map)
}
func frequency_map(arr string) map[string]int{
freq := make(map[string]int)
for _ , char := range arr {
freq[string(char)] = freq[string(char)]+1
}
return freq
}
Output:
Frequency of Array is : map[e:4 f:1 g:2 k:2 o:1 r:1 s:2]
Hence the function frequency_map returns the map which is a string to integer mapping. So we were able to get a frequency map of string by just parsing the string to a function and storing the frequency in a variable.
Similar Reads
Go Tutorial Go or you say Golang is a procedural and statically typed programming language having the syntax similar to C programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language and mainly used in Google
2 min read
Overview
Go Programming Language (Introduction)Go is a procedural programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language. Programs are assembled by using packages, for efficient management of dependencies. This language also supports env
11 min read
How to Install Go on Windows?Prerequisite: Introduction to Go Programming Language Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robe
3 min read
How to Install Golang on MacOS?Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but
4 min read
Hello World in GolangHello, World! is the first basic program in any programming language. Letâs write the first program in the Go Language using the following steps:First of all open Go compiler. In Go language, the program is saved with .go extension and it is a UTF-8 text file.Now, first add the package main in your
3 min read
Fundamentals
Identifiers in Go LanguageIn programming languages, identifiers are used for identification purposes. In other words, identifiers are the user-defined names of the program components. In the Go language, an identifier can be a variable name, function name, constant, statement label, package name, or type. Example: package ma
3 min read
Go KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as an identifier. Doing this will result in a compile-time error. Example: C // Go program to illustrate the // use of key
2 min read
Data Types in GoData types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows: Basic type: Numbers, strings, and booleans come under this category.Aggregate type: Array and structs come under this category.Reference type: Pointer
7 min read
Go VariablesA typical program uses various values that may change during its execution. For Example, a program that performs some operations on the values entered by the user. The values entered by one user may differ from those entered by another user. Hence this makes it necessary to use variables as another
9 min read
Constants- Go LanguageAs the name CONSTANTS suggests, it means fixed. In programming languages also it is same i.e., once the value of constant is defined, it cannot be modified further. There can be any basic data type of constants like an integer constant, a floating constant, a character constant, or a string literal.
6 min read
Go OperatorsOperators are the foundation of any programming language. Thus the functionality of the Go language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In the Go language, operators Can be categorized based on their different functiona
9 min read
Control Statements
Functions & Methods
Functions in Go LanguageIn Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time. Functions may or may not return a value to the caller.Example:Gopackage main import "fmt" // multiply() multiplies two integers and returns
3 min read
Variadic Functions in GoVariadic functions in Go allow you to pass a variable number of arguments to a function. This feature is useful when you donât know beforehand how many arguments you will pass. A variadic function accepts multiple arguments of the same type and can be called with any number of arguments, including n
3 min read
Anonymous function in Go LanguageAn anonymous function is a function that doesnât have a name. It is useful when you want to create an inline function. In Go, an anonymous function can also form a closure. An anonymous function is also known as a function literal.ExampleGopackage main import "fmt" func main() { // Anonymous functio
2 min read
main and init function in GolangThe Go language reserve two functions for special purpose and the functions are main() and init() function.main() functionIn Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a spec
2 min read
What is Blank Identifier(underscore) in Golang?_(underscore) in Golang is known as the Blank Identifier. Identifiers are the user-defined name of the program components used for the identification purpose. Golang has a special feature to define and use the unused variable using Blank Identifier. Unused variables are those variables that are defi
3 min read
Defer Keyword in GolangIn Go language, defer statements delay the execution of the function or method or an anonymous method until the nearby functions returns. In other words, defer function or method call arguments evaluate instantly, but they don't execute until the nearby functions returns. You can create a deferred m
3 min read
Methods in GolangGo methods are like functions but with a key difference: they have a receiver argument, which allows access to the receiver's properties. The receiver can be a struct or non-struct type, but both must be in the same package. Methods cannot be created for types defined in other packages, including bu
3 min read
Structure
Arrays
Slices
Slices in GolangSlices in Go are a flexible and efficient way to represent arrays, and they are often used in place of arrays because of their dynamic size and added features. A slice is a reference to a portion of an array. It's a data structure that describes a portion of an array by specifying the starting index
14 min read
Slice Composite Literal in GoThere are two terms i.e. Slice and Composite Literal. Slice is a composite data type similar to an array which is used to hold the elements of the same data type. The main difference between array and slice is that slice can vary in size dynamically but not an array. Composite literals are used to c
3 min read
How to sort a slice of ints in Golang?In Go, slices provide a flexible way to manage sequences of elements. To sort a slice of ints, the sort package offers a few straightforward functions. In this article we will learn How to Sort a Slice of Ints in Golang.ExampleGopackage main import ( "fmt" "sort" ) func main() { intSlice := []int{42
2 min read
How to trim a slice of bytes in Golang?In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you ar
3 min read
How to split a slice of bytes in Golang?In Golang, you can split a slice of bytes into multiple parts using the bytes.Split function. This is useful when dealing with data like encoded strings, file contents, or byte streams that must be divided by a specific delimiter.Examplepackage mainimport ( "bytes" "fmt")func main() { // Initial byt
3 min read
Strings
Strings in GolangIn the Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where every character is represented by one or more bytes using UTF-8 Encoding. In other words, strings are the immutable chain of arbitrary bytes(including bytes
7 min read
How to Trim a String in Golang?In Go, strings are UTF-8 encoded sequences of variable-width characters, unlike some other languages like Java, python and C++. Go provides several functions within the strings package to trim characters from strings.In this article we will learn how to Trim a String in Golang.Examples := "@@Hello,
2 min read
How to Split a String in Golang?In Go language, strings differ from other languages like Java, C++, and Python. A string in Go is a sequence of variable-width characters, with each character represented by one or more bytes using UTF-8 encoding. In Go, you can split a string into a slice using several functions provided in the str
3 min read
Different ways to compare Strings in GolangIn Go, strings are immutable sequences of bytes encoded in UTF-8. You can compare them using comparison operators or the strings.Compare function. In this article,we will learn different ways to compare Strings in Golang.Examplepackage main import ( "fmt" "strings" ) func main() { s1 := "Hello" s2 :
2 min read
Pointers