Write a Golang program to find the frequency of each element in an array


Examples

Input Array = [1, 3, 4, 3, 2, 3, 4, 0, 2]

Element
1
3
4
2
0
Frequency
1
3
2
2
1

Approach to solve this problem

  • Step 1: Define a method that accepts an array.
  • Step 2: Define a map, where key would be the array’s elements and the starting value is 0.
  • Step 3: Start iterating the input array. If an element is present in the map, then increment the count.
  • Step 4: If the element is not present in the map, then store in map and make its value 1.

Program

Live Demo

package main
import (
   "fmt"
)

func findFrequencyOfArray(arr []int){
   frequency := make(map[int]int)
   for _, item := range arr{
      if frequency[item] == 0{
         frequency[item] = 1
      } else {
         frequency[item]++
      }
   }
   for item, count := range frequency{
      fmt.Printf("%d occurring %d times.\n", item, count)
   }
}

func main(){
   findFrequencyOfArray([]int{2, 2, 5, 1, 3, 5, 0})
}

Output

2 occurring 2 times.
5 occurring 2 times.
1 occurring 1 times.
3 occurring 1 times.
0 occurring 1 times.

Updated on: 04-Feb-2021

477 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements