Problem overview
The function productExceptSelf receives a slice of integers, nums, and returns a slice answer of the same length. Each answer[i] is the product of every element of nums except nums[i]. Division is not allowed, and the extra space must be O(1): the returned slice doesn't count.
For nums = [1, 2, 3, 4] the answer is [24, 12, 8, 6]. For example, answer[2] is 1 * 2 * 4 = 8: the 3 at index 2 is left out. With a zero in the input, such as [-1, 1, 0, -3, 3], every product that includes the zero is zero, so the answer is [0, 0, 9, 0, 0]. Only the position of the zero keeps a non-zero product.
Approach: left products times right products
The obvious way is to multiply all the other elements for each index, which is O(n²). The next idea is to multiply everything once and divide by nums[i], but division is forbidden, and it would also fail whenever the input contains a zero.
The way out is to split "everything except nums[i]" into two parts: the product of everything to the left of i, and the product of everything to the right. Multiply the two parts and nums[i] is never included.
- The left products are prefix products. Each one reuses the one before it: the product left of
iis the product left ofi-1timesnums[i-1]. Nothing lies left of index 0, and a product of no numbers is 1. - The right products are built the same way from the other end. They are not stored in a second slice. Walking from right to left, one running variable holds the product of everything already passed, and each right-side product is used exactly once, as soon as it is known.
For nums = [1, 2, 3, 4], after the first pass answer holds the left products [1, 1, 2, 6]. The second pass multiplies in the right products, which are 24, 12, 4 and 1 for indices 0 to 3, and the result is [24, 12, 8, 6].
Step by step
- Store the length of
numsinn. Both loops use it. - Create
answerwithmake([]int, n), which givesnzeros, and setanswer[0]to 1, the empty product to the left of the first element. - Loop from index 1 to
n - 1. Index 0 is already filled. - Set
answer[i]toanswer[i-1] * nums[i-1]. After the loop,answer[i]is the product of everything left ofi. - Start
suffixat 1. It will hold the product of everything to the right of the current index. The last element has nothing to its right. - Loop from
n - 1down to 0. - Multiply
answer[i]bysuffix. Now it holds left times right. - Multiply
suffixbynums[i], so that it coversnums[i]when the loop moves one step left. The order matters: this line must come after the previous one. - Return
answer.
The solution in Go
func productExceptSelf(nums []int) []int {
n := len(nums)
answer := make([]int, n)
answer[0] = 1
for i := 1; i < n; i++ {
answer[i] = answer[i-1] * nums[i-1]
}
suffix := 1
for i := n - 1; i >= 0; i-- {
answer[i] *= suffix
suffix *= nums[i]
}
return answer
}
The Go details worth a closer look:
make([]int, n)creates a slice of lengthnfilled with zeros, so every index can be written to straight away. A slice made with[]int{}has length 0, and writing toanswer[0]would panic.- Reusing
answeras storage. The first loop readsanswer[i-1], a value it wrote one iteration earlier. That is what makes the prefix products cheap: each is one multiplication. *=is the compound assignmentanswer[i] = answer[i] * suffix. The index expression is evaluated once.- The loop
for i := n - 1; i >= 0; i--works becauseiis a signedint. It stops whenibecomes -1. The same loop with an unsigned type would never end. intis 64 bits on current 64-bit Go builds, so the products, which the constraints keep within 32 bits, can't overflow here.
Complexity
Time: O(n). There are two passes over the slice, each doing one or two multiplications per element.
Space: O(1) extra. The returned answer is required output, and the only other variables are n, suffix and the loop index. Storing the suffix products in a second slice would keep the O(n) time but cost O(n) extra space.
Edge cases and common mistakes
- Zeros. The method never divides, so zeros need no special case.
[5, 0, 2]gives[0, 10, 0], and[0, 0]gives[0, 0]. - Two elements.
[2, 3]gives[3, 2]: each answer is the other element. - Swapping the two lines in the second loop. If
suffix *= nums[i]runs first,nums[i]ends up inside its own product. For[1, 2, 3, 4]every entry would become 24. - Starting
answer[0]at 0.makeleaves it at 0, and every later prefix product would then be 0. It must be set to 1. - An empty slice. The solution reads
answer[0], so an empty input would panic with an index out of range. The constraints guarantee at least two elements.
Testing
[1, 2, 3, 4]gives[24, 12, 8, 6].[-1, 1, 0, -3, 3]gives[0, 0, 9, 0, 0].[2, 3]gives[3, 2].[0, 0]gives[0, 0].[5, 0, 2]gives[0, 10, 0].
