Skip to content

Instantly share code, notes, and snippets.

@tsak
Created June 18, 2019 15:53
Show Gist options
  • Save tsak/7d6780c7ef7e3e257e0099dac8dad35a to your computer and use it in GitHub Desktop.
Save tsak/7d6780c7ef7e3e257e0099dac8dad35a to your computer and use it in GitHub Desktop.
Count unique pairs in an array
package main
import (
"fmt"
)
type Pair struct {
x int32
y int32
}
// This is O(n^2 log n), expectation was O(n^2)
func countPairs(arr []int32, k int64) int32 {
pairs := make(map[Pair]struct{})
for i := 0; i < len(arr); i++ {
for j := 0; j < len(arr); j++ {
if i != j && int64(arr[i] + arr[j]) == k {
x, y := arr[i], arr[j]
if x > y {
x, y = y, x // Sort pair to avoid duplicates
}
pairs[Pair{x,y}]= struct{}{}
}
}
}
return int32(len(pairs))
}
func main() {
fmt.Println(countPairs([]int32{1,3,46,1,3,9}, 47), 1)
fmt.Println(countPairs([]int32{6,6,3,9,3,5,1}, 12), 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment