Skip to content

Commit

Permalink
# ADD - contiguous subarray sum
Browse files Browse the repository at this point in the history
  • Loading branch information
morishjs committed Jun 4, 2019
1 parent daa094c commit 195eb1a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/contiguous_subarray_sum.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Given an array of numbers, return true if there is a contiguous subarray that sums up to a certain number n.

// const arr = [1, 2, 3], sum = 5
// subarraySum(arr, sum)
// // true

// const arr = [11, 21, 4], sum = 9
// subarraySum(arr, sum)
// // false
// In the above examples, 2, 3 sum up to 5 so we return true. On the other hand, no subarray in [11, 21, 4] can sum up to 9.

// solution: https://algodaily.com/challenges/contiguous-subarray-sum

package main

func subarraySum(arr []int, sum int) bool {
for i, v := range arr {
if i+1 < len(arr) && v+arr[i+1] == sum {
return true
}
}

return false
}
38 changes: 38 additions & 0 deletions src/contiguous_subarray_sum_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import "testing"

func Test_subarraySum(t *testing.T) {
type args struct {
arr []int
sum int
}
tests := []struct {
name string
args args
want bool
}{
{
"`sum` number exists",
args{[]int{1, 2, 3}, 5},
true,
},
{
"`sum` number exists",
args{[]int{1, 2, 3}, 3},
true,
},
{
"`sum` number does not exists",
args{[]int{11, 21, 4}, 5},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := subarraySum(tt.args.arr, tt.args.sum); got != tt.want {
t.Errorf("subarraySum() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 195eb1a

Please sign in to comment.