Skip to content

Commit

Permalink
Merge ea0fb1f into 36687a4
Browse files Browse the repository at this point in the history
  • Loading branch information
dalmirdasilva committed Jan 20, 2021
2 parents 36687a4 + ea0fb1f commit 51accd3
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
go.mod
.idea
19 changes: 19 additions & 0 deletions day2/problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,25 @@ func ProductsExceptI(arr []int) []int {
return result
}

// ProductsExceptINoDivisionLinear returns an array with the products of all numbers
// except the value at the i-th position. Without using division.
// O(N) time complexity.
// O(1) space complexity.
func ProductsExceptINoDivisionLinear(arr []int) []int {
result := make([]int, len(arr))
total := 1
for i := 0; i < len(arr); i++ {
result[i] = total
total *= arr[i]
}
total = 1
for i := len(arr) - 1; i >= 0; i-- {
result[i] *= total
total *= arr[i]
}
return result
}

// ProductsExceptINoDivision returns an array with the products of all numbers
// except the value at the i-th position. Without using division.
// O(N^2) time complexity.
Expand Down
15 changes: 15 additions & 0 deletions day2/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ func TestProductsExceptI(t *testing.T) {
}
}
})
t.Run("ProductsExceptINoDivisionLinear", func(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := ProductsExceptINoDivisionLinear(tc.input); !reflect.DeepEqual(result, tc.expected) {
t.Error("didn't get what I expected")
}
}
})
t.Run("ProductsExceptINoDivision", func(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
Expand All @@ -39,6 +47,13 @@ func BenchmarkProductsExceptI(b *testing.B) {
}
}
})
b.Run("ProductsExceptINoDivisionLinear", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
ProductsExceptINoDivisionLinear(tc.input)
}
}
})
b.Run("ProductsExceptINoDivision", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
Expand Down

0 comments on commit 51accd3

Please sign in to comment.