Arrays / Strings / Hashing · hash set, deduplication
Given an array of integers nums and a target, return all unique pairs of values (not indices) that sum to target. Each pair should be sorted internally (smaller value first), and the list of pairs should be deduplicated.
nums = [1, 5, 1, 4, 2], target = 6 -> [[1, 5], [2, 4]]
Even though 1 appears twice, the pair [1, 5] is only reported once.
package main
import (
"fmt"
"sort"
)
func twoSumPairs(nums []int, target int) [][]int {
seen := make(map[int]bool)
pairs := make(map[[2]int]bool) // a sorted pair is the dedup key
for _, v := range nums {
comp := target - v
if seen[comp] {
lo, hi := comp, v
if lo > hi {
lo, hi = hi, lo
}
pairs[[2]int{lo, hi}] = true
}
seen[v] = true
}
out := make([][]int, 0, len(pairs))
for p := range pairs {
out = append(out, []int{p[0], p[1]})
}
sort.Slice(out, func(i, j int) bool { return out[i][0] < out[j][0] })
return out
}
func main() {
fmt.Println(twoSumPairs([]int{1, 5, 1, 4, 2}, 6)) // [[1 5] [2 4]]
}
v, its partner is target - v. If that partner is already in the seen set, you have found a pair.[1,5] and [5,1] become the same key. A fixed-size array [2]int is comparable in Go, so it can be a map key directly.map[[2]int]bool means a pair that occurs many times is only kept once — that is what handles the duplicate 1.seen[v] = true after the lookup so a single element can't pair with itself; a value only pairs with a partner that appeared earlier in the scan.Time: O(n) to scan, plus O(p log p) to sort the p output pairs. Space: O(n) for the seen set and the pair set.