Skip to content

Instantly share code, notes, and snippets.

@kahunacohen
Last active April 8, 2023 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kahunacohen/f55d088afa2a5c58cbc8c1affb36821d to your computer and use it in GitHub Desktop.
Save kahunacohen/f55d088afa2a5c58cbc8c1affb36821d to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sort"
)
// Implementation of sum of three ints. Do any three ints
// in the given slice sum up to the target?
// Interate through eacn int. For each iteration set low and
// high pointers for the elements to the right of the current
// element and adjust each pointer depending on whether the sum of
// the current element + left + right is less than or greater than
// the target.
func isSumOf3(xs []int, target int) bool {
if len(xs) < 3 {
return false
}
sort.Ints(xs)
highIndx := len(xs) - 1
for i, x := range xs {
lowIndx := i + 1
for lowIndx < highIndx {
lowVal := xs[lowIndx]
highVal := xs[highIndx]
sum := x + lowVal + highVal
if sum < target {
lowIndx = lowIndx + 1
} else if sum > target {
highIndx = highIndx - 1
} else {
return true
}
}
}
return false
}
func main() {
xs := []int{-1, 2, 1, -4, 5, -3}
fmt.Println(isSumOf3(xs, -8))
xs = []int{1, 2, 3}
fmt.Println(isSumOf3(xs, 6))
xs = []int{1, 2, 7}
fmt.Println(isSumOf3(xs, 6))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment