Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if map has duplicate values in Go

Tags:

go

Consider the following map

mymap := make(map[string]string)
mymap["a"] = "one"
mymap["b"] = "two"
mymap["c"] = "one"

How to determine if the values are unique?

One strategy is to iterate through the map, create a slice of the values. Then iterate through the slice to find duplicates. Is there a better way?

like image 789
Vinay Sheshadri Avatar asked Sep 05 '25 20:09

Vinay Sheshadri


1 Answers

If you just need true/false of whether there are dupes, without needing to know which values are dupes or how many dupes there are, the most efficient structure to use to track existing values is a map with empty struct values.

See here (pasted below for convenience):

package main

import (
    "fmt"
)

func hasDupes(m map[string]string) bool {
    x := make(map[string]struct{})

    for _, v := range m {
        if _, has := x[v]; has {
            return true
        }
        x[v] = struct{}{}
    }

    return false
}

func main() {
    mapWithDupes := make(map[string]string)
    mapWithDupes["a"] = "one"
    mapWithDupes["b"] = "two"
    mapWithDupes["c"] = "one"

    fmt.Println(hasDupes(mapWithDupes)) // prints true

    mapWithoutDupes := make(map[string]string)
    mapWithoutDupes["a"] = "one"
    mapWithoutDupes["b"] = "two"
    mapWithoutDupes["c"] = "three"

    fmt.Println(hasDupes(mapWithoutDupes)) // prints false
}
like image 58
Amit Kumar Gupta Avatar answered Sep 08 '25 10:09

Amit Kumar Gupta