Start learning free

LESSON 36 OF 314 · PARTIAL SUMS #1

Product of Array Except Self in Go: O(n), No Division

Practice O(n) Read the full explanation

You get an array of integers nums.

Return an array answer of the same length.

answer[i] is the product of all the numbers in nums, except the one at index i.

Don't use division.

 

Example 1:

Input: nums = [2,5,1,3]
Output: [15,6,30,10]
Explanation:
answer[0] = 5 * 1 * 3 = 15,
answer[1] = 2 * 1 * 3 = 6,
answer[2] = 2 * 5 * 3 = 30,
answer[3] = 2 * 5 * 1 = 10.

Example 2:

Input: nums = [4,0,-2,5]
Output: [0,-40,0,0]
Explanation: Every product that includes the 0 is 0.
Only answer[1] leaves the 0 out:
answer[1] = 4 * (-2) * 5 = -40.

Example 3:

Input: nums = [0,6,0]
Output: [0,0,0]
Explanation: There are two zeros.
Every product still includes at least one of them.

 

Constraints:

  • nums has 2 to 100,000 numbers.
  • Each number is from -30 to 30.
  • Every answer[i] fits in a 32-bit signed integer.
  • So does the product of all the numbers before any index, or after it.

Note:

Your algorithm should run in O(n) time and use O(1) extra space: the returned array doesn't count.

STEP 1 OF 9
    Ctrl + Enter to check

    GO · PARTIAL SUMS #1

    Product Of Array Except Self in Go, explained

    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 i is the product left of i-1 times nums[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

    1. Store the length of nums in n. Both loops use it.
    2. Create answer with make([]int, n), which gives n zeros, and set answer[0] to 1, the empty product to the left of the first element.
    3. Loop from index 1 to n - 1. Index 0 is already filled.
    4. Set answer[i] to answer[i-1] * nums[i-1]. After the loop, answer[i] is the product of everything left of i.
    5. Start suffix at 1. It will hold the product of everything to the right of the current index. The last element has nothing to its right.
    6. Loop from n - 1 down to 0.
    7. Multiply answer[i] by suffix. Now it holds left times right.
    8. Multiply suffix by nums[i], so that it covers nums[i] when the loop moves one step left. The order matters: this line must come after the previous one.
    9. 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 length n filled with zeros, so every index can be written to straight away. A slice made with []int{} has length 0, and writing to answer[0] would panic.
    • Reusing answer as storage. The first loop reads answer[i-1], a value it wrote one iteration earlier. That is what makes the prefix products cheap: each is one multiplication.
    • *= is the compound assignment answer[i] = answer[i] * suffix. The index expression is evaluated once.
    • The loop for i := n - 1; i >= 0; i-- works because i is a signed int. It stops when i becomes -1. The same loop with an unsigned type would never end.
    • int is 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. make leaves 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].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free