LeetCode Problem: Product of Array Except Self
Problem statement:
Given an integer array (nums), return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input:
[1,2,3,4]
Expected output:
[24,12,8,6]
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/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
}