Skip to content

Commit

Permalink
Merge 45bd037 into c96deb1
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 2, 2018
2 parents c96deb1 + 45bd037 commit 1d38235
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
39 changes: 39 additions & 0 deletions day102/problem.go
Original file line number Diff line number Diff line change
@@ -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
}
53 changes: 53 additions & 0 deletions day102/problem_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}

0 comments on commit 1d38235

Please sign in to comment.