Skip to content

Instantly share code, notes, and snippets.

@jboursiquot
Last active March 6, 2019 00:00
Show Gist options
  • Select an option

  • Save jboursiquot/ccac53ff107f256052e4e915419ce7be to your computer and use it in GitHub Desktop.

Select an option

Save jboursiquot/ccac53ff107f256052e4e915419ce7be to your computer and use it in GitHub Desktop.

Two-Number Sum

Write a function that takes as parameters a non-empty slice of integers and an integer representing a target sum. Your task is to return the pair of numbers within the input slice that add up to the target sum given. If no numbers in the input slice add up to the given target sum, return an empty slice. You may assume that there will be no more than one pair of numbers from the input slice that add up to the target sum.

Hint: There are several ways to do this which vary in efficiency. First focus on solving it and only then on optimizing it.

You may use the test below to exercise your solution.

package sum
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTwoNumberSum(t *testing.T) {
cases := []struct {
name string
numbers []int
sum int
expected []int
}{
{name: "one", numbers: []int{4, 6}, sum: 10, expected: []int{4, 6}},
{name: "two", numbers: []int{4, 6, 1}, sum: 5, expected: []int{1, 4}},
{name: "three", numbers: []int{6, 4}, sum: 10, expected: []int{4, 6}},
{name: "four", numbers: []int{5, 7, 5}, sum: 10, expected: []int{5, 5}},
{name: "five", numbers: []int{4, 0, 6}, sum: 10, expected: []int{4, 6}},
{name: "six", numbers: []int{-5, 5, 15}, sum: 10, expected: []int{-5, 15}},
{name: "seven", numbers: []int{-1, 5, 15}, sum: 10, expected: []int{}},
{name: "eight", numbers: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, sum: 17, expected: []int{8, 9}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.expected, twoNumberSum(tc.numbers, tc.sum))
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment