diff --git a/README.md b/README.md index 231ca71..cb56aaf 100644 --- a/README.md +++ b/README.md @@ -111,3 +111,4 @@ problems from * [Day 99](https://github.com/vaskoz/dailycodingproblem-go/issues/205) * [Day 100](https://github.com/vaskoz/dailycodingproblem-go/issues/209) * [Day 101](https://github.com/vaskoz/dailycodingproblem-go/issues/212) +* [Day 102](https://github.com/vaskoz/dailycodingproblem-go/issues/214) diff --git a/day102/problem.go b/day102/problem.go new file mode 100644 index 0000000..87170ba --- /dev/null +++ b/day102/problem.go @@ -0,0 +1,39 @@ +package day102 + +// ContiguousSumBrute uses brute-force to return the +// contiguous subset that sums to K. +// Runtime is O(N^2) and O(1) space. +func ContiguousSumBrute(nums []int, k int) []int { + var result []int + for i := range nums { + var sum int + for j := i; j < len(nums); j++ { + sum += nums[j] + if sum == k { + return nums[i : j+1] + } + } + } + return result +} + +// ContiguousSumFaster uses a window to return the +// contiguous subset that sums to K. +// Runtime is O(N) and O(1) space. +func ContiguousSumFaster(nums []int, k int) []int { + var result []int + var sum, begin int + for end := 0; end < len(nums); end++ { + sum += nums[end] + if sum == k { + result = nums[begin : end+1] + break + } else if sum > k { + sum -= nums[begin] + sum -= nums[end] + begin++ + end-- + } + } + return result +} diff --git a/day102/problem_test.go b/day102/problem_test.go new file mode 100644 index 0000000..f973aaf --- /dev/null +++ b/day102/problem_test.go @@ -0,0 +1,53 @@ +package day102 + +import ( + "reflect" + "testing" +) + +var testcases = []struct { + input []int + k int + expected []int +}{ + {[]int{1, 2, 3, 4, 5}, 9, []int{2, 3, 4}}, + {[]int{1, 2, 3, 4, 5}, 16, nil}, + {[]int{1, 2, 3, 4, 5}, 15, []int{1, 2, 3, 4, 5}}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}, + 49, []int{4, 5, 6, 7, 8, 9, 10}}, +} + +func TestContiguousSumBrute(t *testing.T) { + t.Parallel() + for _, tc := range testcases { + if result := ContiguousSumBrute(tc.input, tc.k); !reflect.DeepEqual(tc.expected, result) { + t.Errorf("Expected %v got %v", tc.expected, result) + } + } +} + +func BenchmarkContiguousSumBrute(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, tc := range testcases { + ContiguousSumBrute(tc.input, tc.k) + } + } +} + +func TestContiguousSumFaster(t *testing.T) { + t.Parallel() + for _, tc := range testcases { + if result := ContiguousSumFaster(tc.input, tc.k); !reflect.DeepEqual(tc.expected, result) { + t.Errorf("Expected %v got %v", tc.expected, result) + } + } +} + +func BenchmarkContiguousSumFaster(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, tc := range testcases { + ContiguousSumFaster(tc.input, tc.k) + } + } +}