Skip to content

Commit

Permalink
improve performance of ContainsDuplicates
Browse files Browse the repository at this point in the history
  • Loading branch information
BrendanChou committed May 23, 2024
1 parent 5861c04 commit 003ad0d
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions protocol/lib/collections.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ import (

// ContainsDuplicates returns true if the slice contains duplicates, false if not.
func ContainsDuplicates[V comparable](values []V) bool {
seenValues := make(map[V]bool)
for _, val := range values {
if _, exists := seenValues[val]; exists {
// Store each value as a key in the mapping.
seenValues := make(map[V]struct{}, len(values))
for i, val := range values {
// Add the value to the mapping.
seenValues[val] = struct{}{}

// Return early if the size of the mapping did not grow.
if len(seenValues) <= i {
return true
}

seenValues[val] = true
}

return false
Expand Down

0 comments on commit 003ad0d

Please sign in to comment.