MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / tripletSum

Function tripletSum

go/Two Pointers/triplet_sum.go:1–27  ·  view source on GitHub ↗
(nums []int)

Source from the content-addressed store, hash-verified

1func tripletSum(nums []int) [][]int {
2 triplets := [][]int{}
3 sort.Ints(nums)
4
5 for i := 0; i < len(nums); i++ {
6 // Optimization: triplets consisting of only positive numbers
7 // will never sum to 0.
8
9 if nums[i] > 0 {
10 break
11 }
12
13 // To avoid duplicate triplets, skip 'a' if it's the same as
14 // the previous number.
15 if i > 0 && nums[i] == nums[i-1] {
16 continue
17 }
18
19 // Find all pairs that sum to a target of '-a' (-nums[i]).
20 pairs := pairSumSortedAllPairs(nums, i+1, -nums[i])
21 for _, pair := range pairs {
22 triplets = append(triplets, []int{nums[i], pair[0], pair[1]})
23 }
24 }
25
26 return triplets
27}
28
29func pairSumSortedAllPairs(nums []int, start int, target int) [][]int {
30 pairs := [][]int{}

Callers

nothing calls this directly

Calls 1

pairSumSortedAllPairsFunction · 0.70

Tested by

no test coverage detected