diff --git a/pkg/three_sum/main.go b/pkg/three_sum/main.go new file mode 100644 index 0000000..2a73d9a --- /dev/null +++ b/pkg/three_sum/main.go @@ -0,0 +1,41 @@ +package three_sum + +import ( + "slices" +) + +func TwoSum(numbers []int, target int, solutions map[[3]int]bool) { + start := 0 + end := len(numbers) - 1 + + for start < end { + sum := numbers[start] + numbers[end] + + if sum < target { + start++ + } else if sum > target { + end-- + } else { + solutions[[3]int{-target, numbers[start], numbers[end]}] = true + start++ + } + } +} + +func ThreeSum(nums []int) [][]int { + slices.Sort(nums) + + solutions := map[[3]int]bool{} + + for i := range nums { + TwoSum(nums[i+1:], -nums[i], solutions) + } + + result := [][]int{} + + for solution := range solutions { + result = append(result, solution[:]) + } + + return result +} diff --git a/pkg/three_sum/main_test.go b/pkg/three_sum/main_test.go new file mode 100644 index 0000000..dde9db5 --- /dev/null +++ b/pkg/three_sum/main_test.go @@ -0,0 +1,26 @@ +package three_sum_test + +import ( + "testing" + + "git.maximhutz.com/practice/pkg/three_sum" + "github.com/stretchr/testify/assert" +) + +func Test1(t *testing.T) { + assert.ElementsMatch(t, + [][]int{{-1, -1, 2}, {-1, 0, 1}}, + three_sum.ThreeSum([]int{-1, 0, 1, 2, -1, -4})) +} + +func Test2(t *testing.T) { + assert.Equal(t, + [][]int{}, + three_sum.ThreeSum([]int{0, 1, 1})) +} + +func Test3(t *testing.T) { + assert.Equal(t, + [][]int{{0, 0, 0}}, + three_sum.ThreeSum([]int{0, 0, 0})) +}