Frequency map in go

A frequency map is just a fancy word for a hash map that tracks the number of occurrences of an element in a collection.

If we have a slice in go and we want to know exactly how many times each element in the slice occurs in the slice, we can build a frequency map out of it; then we can just hash the element as key in the map, and it should take O(1) to get the frequency.

A basic way to implement it can be:

type FrequencyMap[T comparable] struct {
	kv map[T]int
}

func PopulateFrequencyMap[T comparable](elements []T) *FrequencyMap[T]{
	fmap := &FrequencyMap[T]{
		kv: make(map[T]int),
	}

	for _, element := range elements {
		fmap.kv[element]++
	}

	return fmap
}

func (f *FrequencyMap[T]) Get(element T) int {
	return f.kv[element]
}

func (f *FrequencyMap[T]) Add(element T) {
	f.kv[element]++
}

func (f *FrequencyMap[T]) Remove(element T) {
	if fq, ok := f.kv[element]; ok {
		if fq <= 1 {
			delete(f.kv, element)
			return
		}
		f.kv[element]--
	}
}

func (f *FrequencyMap[T]) MostFrequent() (element T, f int, ok bool) {
	for k, v := range f.kv {
		if v > f {
			element = k
			f = v
			ok = true
		}
	}

	return element, f, ok
}

bye now.

Leave a Reply