Counting how often each element appears in a collection
is one of the most common uses of a hash map. In Go,
map[T]int is the standard frequency counter.
Use when: you need to detect duplicates, find the most common element, or group items by count.
The simplest application: checking if any element
appears more than once. We use map[int]struct{}
as a set — struct{} uses zero bytes of memory.
Go doesn’t have a built-in set, but a map with empty struct values is the idiomatic equivalent.
A more general version: count the frequency of every element and return the full frequency map.
Incrementing a missing key in Go starts from the zero value (0 for int), so no initialization needed.
Trace: nums = [1, 2, 3, 1]
hasDuplicates: i=0: num=1, seen={} -> add 1 i=1: num=2, seen={1} -> add 2 i=2: num=3, seen={1,2} -> add 3 i=3: num=1, seen={1,2,3} -> found! return true
frequencyMap: result: {1:2, 2:1, 3:1}
func hasDuplicates(nums []int) bool {
seen := make(map[int]struct{})
for _, num := range nums {
if _, exists := seen[num]; exists {
return true
}
seen[num] = struct{}{}
}
return false
}
func frequencyMap(nums []int) map[int]int {
freq := make(map[int]int)
for _, num := range nums {
freq[num]++
}
return freq
}
func main() {
fmt.Println(hasDuplicates([]int{1, 2, 3, 1}))
fmt.Println(hasDuplicates([]int{1, 2, 3, 4}))
freq := frequencyMap([]int{1, 2, 3, 1, 2, 1})
fmt.Println(freq)
}