product-of-array-except-self

This commit is contained in:
Gleb Koval 2021-11-05 12:53:13 +00:00
parent 93fcca2976
commit d31b918c96
No known key found for this signature in database
GPG Key ID: 7C89CDC822F8392B
1 changed files with 18 additions and 0 deletions

View File

@ -0,0 +1,18 @@
package main
// Time: O(n)
// Space: O(1)
func productExceptSelf(nums []int) []int {
l := len(nums)
answer := make([]int, l)
answer[0] = 1
for idx := 1; idx < l; idx++ {
answer[idx] = answer[idx-1] * nums[idx-1]
}
m := 1
for idx := l - 1; idx >= 0; idx-- {
answer[idx] *= m
m *= nums[idx]
}
return answer
}