Skip to content

Instantly share code, notes, and snippets.

@kahunacohen
Last active April 6, 2023 21:00
Show Gist options
  • Save kahunacohen/702eaaa158a73254cbc821b6aa551376 to your computer and use it in GitHub Desktop.
Save kahunacohen/702eaaa158a73254cbc821b6aa551376 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sort"
)
// Implementation of sum of two ints. Do any two ints
// in the given slice sum up to the target? Leverages
// sorting O(n logn) and two pointers. If the sum of the
// pointed to ints are less than the target, then we move
// the left pointer right. If the sum is greater than the target,
// then we move the right pointer left until either we find
// a pair that sums to the target or the two pointers meet.
// A naaive approach would be a nested loop in order to test
// every combination. That, of course, would be O(n^2) time, much
// worse than sorting a slice.
func isSumOf2(xs []int, target int) bool {
sort.Ints(xs)
leftPointer := 0
rightPointer := len(xs) - 1
for leftPointer < rightPointer {
sum := xs[leftPointer] + xs[rightPointer]
if sum > target {
rightPointer = rightPointer - 1
} else if sum < target {
leftPointer = leftPointer + 1
} else {
return true
}
}
return false
}
func main() {
xs := []int{5, 2, 3, 1}
fmt.Println(isSumOf2(xs, 4))
xs = []int{5, 2, 3, 1}
fmt.Println(isSumOf2(xs, 9))
xs = []int{1}
fmt.Println(isSumOf2(xs, 9))
xs = []int{}
fmt.Println(isSumOf2(xs, 9))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment