diff --git a/README.md b/README.md index 14fc1f8..027014b 100644 --- a/README.md +++ b/README.md @@ -178,3 +178,4 @@ problems from * [Day 164](https://github.com/vaskoz/dailycodingproblem-go/issues/340) * [Day 165](https://github.com/vaskoz/dailycodingproblem-go/issues/343) * [Day 166](https://github.com/vaskoz/dailycodingproblem-go/issues/346) +* [Day 167](https://github.com/vaskoz/dailycodingproblem-go/issues/347) diff --git a/day167/problem.go b/day167/problem.go new file mode 100644 index 0000000..0a3c15e --- /dev/null +++ b/day167/problem.go @@ -0,0 +1,34 @@ +package day167 + +// Pair represents indicies that correspond to words +// that when concatenated result in a palindrome. +type Pair struct { + First, Second int +} + +// PairsPalindromes returns a slice of Pairs. +// Runs in O(N^2) time. +func PairsPalindromes(words []string) []Pair { + var result []Pair + for i, first := range words { + for j, second := range words { + if i == j { + continue + } + combined := first + second + if isPalindrome(combined) { + result = append(result, Pair{i, j}) + } + } + } + return result +} + +func isPalindrome(s string) bool { + for i := 0; i < len(s)/2; i++ { + if s[i] != s[len(s)-1-i] { + return false + } + } + return true +} diff --git a/day167/problem_test.go b/day167/problem_test.go new file mode 100644 index 0000000..36f2dbf --- /dev/null +++ b/day167/problem_test.go @@ -0,0 +1,30 @@ +package day167 + +import ( + "reflect" + "testing" +) + +var testcases = []struct { + words []string + expected []Pair +}{ + {[]string{"code", "edoc", "da", "d"}, []Pair{{0, 1}, {1, 0}, {2, 3}}}, +} + +func TestPairsPalindromes(t *testing.T) { + t.Parallel() + for _, tc := range testcases { + if result := PairsPalindromes(tc.words); !reflect.DeepEqual(tc.expected, result) { + t.Errorf("Expected %v got %v", tc.expected, result) + } + } +} + +func BenchmarkPairsPalindromes(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, tc := range testcases { + PairsPalindromes(tc.words) + } + } +}