0
0
GoProgramBeginner · 2 min read

Go Program to Find Frequency of Elements

In Go, use a map to count frequencies by iterating over a slice and incrementing counts like freq[element]++ inside a loop.
📋

Examples

Input[1, 2, 2, 3, 3, 3]
Outputmap[1:1 2:2 3:3]
Input["apple", "banana", "apple", "orange", "banana", "banana"]
Outputmap[apple:2 banana:3 orange:1]
Input[]
Outputmap[]
🧠

How to Think About It

To find how many times each element appears, think of a box (map) where you keep counts. For each element in the list, check if it's already in the box; if yes, add one to its count, if no, start its count at one.
📐

Algorithm

1
Create an empty map to hold element frequencies.
2
Go through each element in the input list.
3
For each element, increase its count in the map by one.
4
After processing all elements, return or print the map with frequencies.
💻

Code

go
package main

import "fmt"

func main() {
    elements := []int{1, 2, 2, 3, 3, 3}
    freq := make(map[int]int)

    for _, e := range elements {
        freq[e]++
    }

    fmt.Println(freq)
}
Output
map[1:1 2:2 3:3]
🔍

Dry Run

Let's trace the example [1, 2, 2, 3, 3, 3] through the code

1

Initialize frequency map

freq = {} (empty map)

2

Process element 1

freq[1] = 1

3

Process element 2

freq[2] = 1

4

Process element 2 again

freq[2] = 2

5

Process element 3

freq[3] = 1

6

Process element 3 again

freq[3] = 2

7

Process element 3 again

freq[3] = 3

ElementFrequency Map
1map[1:1]
2map[1:1 2:1]
2map[1:1 2:2]
3map[1:1 2:2 3:1]
3map[1:1 2:2 3:2]
3map[1:1 2:2 3:3]
💡

Why This Works

Step 1: Use a map for counting

A map in Go stores keys and values, perfect for linking each element to its count.

Step 2: Increment count for each element

For every element, increase its count by one using freq[element]++.

Step 3: Print the final frequency map

After counting all elements, printing the map shows how many times each appeared.

🔄

Alternative Approaches

Using struct with slice for fixed known elements
go
package main

import "fmt"

func main() {
    elements := []int{1, 2, 2, 3, 3, 3}
    var freq [4]int // index 0 unused

    for _, e := range elements {
        freq[e]++
    }

    fmt.Println(freq[1:], "(counts for 1,2,3)")
}
This uses an array for counting when elements are small integers; it's faster but less flexible.
Using a custom frequency function returning map
go
package main

import "fmt"

func frequency(elements []string) map[string]int {
    freq := make(map[string]int)
    for _, e := range elements {
        freq[e]++
    }
    return freq
}

func main() {
    fruits := []string{"apple", "banana", "apple"}
    fmt.Println(frequency(fruits))
}
This separates logic into a reusable function, improving code organization.

Complexity: O(n) time, O(k) space

Time Complexity

The program loops once through all n elements, so time grows linearly with input size.

Space Complexity

The map stores counts for k unique elements, so space depends on distinct values.

Which Approach is Fastest?

Using a map is flexible and fast for any element type; arrays are faster but only for small integer ranges.

ApproachTimeSpaceBest For
Map countingO(n)O(k)Any element type, unknown range
Array countingO(n)O(m)Small integer elements with known max m
Function abstractionO(n)O(k)Reusable code, better organization
💡
Use a map with element type as key and int as value to count frequencies efficiently.
⚠️
Beginners often forget to initialize the map before counting, causing runtime errors.