DevPath

← All problems

Product of Array Except Self

Medium arrays · prefix-sum

Description

Return an array where each position holds the product of every other element. Do not use division.

Constraints

2 <= n <= 100000

Examples

Input: nums = [1,2,3,4]

Output: [24,12,8,6]

Hints (1)
  • Build prefix products from the left, then multiply by suffix products from the right.

Solutions

Left prefix pass then right suffix pass. · Time O(n) · Space O(1) extra

func productExceptSelf(nums []int) []int {
    n := len(nums)
    out := make([]int, n)
    prefix := 1
    for i := 0; i < n; i++ {
        out[i] = prefix
        prefix *= nums[i]
    }
    suffix := 1
    for i := n - 1; i >= 0; i-- {
        out[i] *= suffix
        suffix *= nums[i]
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account