// Given a list of integers xs and an integer k, how many (not // necessarily adjacent) pairs of integers that sum to k can be // removed from xs? // An exercise from Leetcode. // Related to the “two sum” problem, which just asks if any such pairs // exist: // I did this in Golang because Python is IRC-unfriendly, but // surprisingly it came out to be shorter in Golang than in Python, // due to Golang being more loosey-goosey about initialization. package main func removals(xs []int, k int) (n int) { seen := map[int]int{} for _, x := range xs { if seen[k - x] != 0 { seen[k - x]-- n++ } else { seen[x]++ } } return } // seen := map[int]int{}; n := 0; for _, x := range xs {y := k - x; if seen[y] != 0 {seen[y]--; n++} else {seen[x]++}} func main() { xs := []int{3, 1, 3, 5, 3} println(removals(xs, 6)) }