Product of Array Except Self
Problem statement
Build an output array where index i holds the product of every value in nums except nums[i]. Aim for linear time and avoid dividing by nums[i].
Example:
Input:
[1, 2, 3, 4]
Expected output:
[24, 12, 8, 6]
Practice on LeetCode: Product of Array Except Self
Golang Solution
func productExceptSelf(nums []int) []int {
n := len(nums)
left := make([]int, n)
right := make([]int, n)
answer := make([]int, n)
left[0] = 1
left[1] = nums[0]
i := 2
for i < n {
left[i] = left[i-1] * nums[i-1]
i += 1
}
right[n-1] = 1
right[n-2] = nums[n-1]
j := n-3
for j >= 0 {
right[j] = right[j+1] * nums[j+1]
j -= 1
}
for i := 0; i < n; i++ {
answer[i] = left[i] * right[i]
}
return answer
}
