Arrays / Strings / Hashing · prefix and suffix products
Given an array nums, return an array output where output[i] is the product of all elements of nums except nums[i]. Solve it without division and in O(n) time.
[1, 2, 3, 4] -> [24, 12, 8, 6]
package main
import "fmt"
func productExceptSelf(nums []int) []int {
n := len(nums)
out := make([]int, n)
prefix := 1 // product of everything to the left of i
for i := 0; i < n; i++ {
out[i] = prefix
prefix *= nums[i]
}
suffix := 1 // product of everything to the right of i
for i := n - 1; i >= 0; i-- {
out[i] *= suffix
suffix *= nums[i]
}
return out
}
func main() {
fmt.Println(productExceptSelf([]int{1, 2, 3, 4})) // [24 12 8 6]
}
output[i] equals the product of everything before i times the product of everything after i — which never includes nums[i] itself, so no division is needed.out[i] with the running product of all earlier elements (prefix), then fold nums[i] into prefix.out[i] by the running product of all later elements (suffix), then fold nums[i] into suffix.Time: O(n), two linear passes. Space: O(1) extra (the output array aside).