Skip to content

Commit

Permalink
day 102: add negatives tolerant solution
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 2, 2018
1 parent f3cd981 commit 545bcdb
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
23 changes: 23 additions & 0 deletions day102/problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,26 @@ func ContiguousSumNonNegative(nums []int, k int) []int {
}
return result
}

// ContiguousSumNegatives returns the
// contiguous subset that sums to K.
// This implementation tolerates negative values.
// Runtime is O(N) and O(N) space.
func ContiguousSumNegatives(nums []int, k int) []int {
var result []int
var sum int
m := make(map[int]int)
for i := range nums {
sum += nums[i]
if sum-k == 0 {
result = nums[0 : i+1]
break
}
if start, found := m[sum-k]; found {
result = nums[start+1 : i+1]
break
}
m[sum] = i
}
return result
}
25 changes: 25 additions & 0 deletions day102/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,28 @@ func BenchmarkContiguousSumNonNegative(b *testing.B) {
}
}
}

func TestContiguousSumNegatives(t *testing.T) {
t.Parallel()
for _, tc := range nonNegativeTestcases {
if result := ContiguousSumNegatives(tc.input, tc.k); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
for _, tc := range negativeTestcases {
if result := ContiguousSumNegatives(tc.input, tc.k); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkContiguousSumNegatives(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range nonNegativeTestcases {
ContiguousSumNegatives(tc.input, tc.k)
}
for _, tc := range negativeTestcases {
ContiguousSumNegatives(tc.input, tc.k)
}
}
}

0 comments on commit 545bcdb

Please sign in to comment.