package main
import (
"fmt"
"math"
)
// MinOccurrence finds the element with the lowest frequency in a slice.
// It returns the element and true on success, or the zero value and false if the slice is empty.
func MinOccurrence[T comparable](slice []T) (T, bool) {
if len(slice) == 0 {
var zero T
return zero, false
}
// 1. Tally element frequencies in O(N) time
counts := make(map[T]int, len(slice))
for _, item := range slice {
counts[item]++
}
// 2. Find the element with the minimum frequency in O(K) time
var minElement T
minCount := math.MaxInt
for item, count := range counts {
if count < minCount {
minCount = count
minElement = item
}
}
return minElement, true
}
func main() {
slc := []int{1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3}
if result, ok := MinOccurrence(slc); ok {
fmt.Println(result) // Output: 5
} else {
fmt.Println("The slice was empty.")
}
}
/*
run:
5
*/