Start learning free

LESSON 320 OF 673 · PARTIAL SUMS #1

Product of Array Except Self in Python: O(n) Without Division

Practice O(n) Read the full explanation

You get a list of integers nums.

Return a list 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 list doesn't count.

STEP 1 OF 9
    Ctrl + Enter to check

    PYTHON · PARTIAL SUMS #1

    Product Of Array Except Self in Python, explained

    Problem overview

    The method productExceptSelf receives a list of integers, nums, and returns a list 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 method must run in O(n) time with O(1) extra space, not counting the returned list.

    For nums = [1, 2, 3, 4] the answer is [24, 12, 8, 6]: the first entry is 2 * 3 * 4, the second is 1 * 3 * 4, and so on. For [-1, 1, 0, -3, 3] the answer is [0, 0, 9, 0, 0]. Every product that includes the zero is zero, and only the entry at the zero's own index leaves it out.

    Approach: left products times right products

    The obvious plan multiplies everything and divides by nums[i]. Besides being forbidden, it breaks as soon as the list contains a zero, because dividing by zero is an error. The brute-force alternative multiplies the other n - 1 elements for every index, which is O(n²).

    The way out is to split each product in two. The product of everything except nums[i] is the product of everything to its left times the product of everything to its right. Both sides can be built with running products, like a running sum, in one pass each:

    • Going left to right, store in answer[i] the product of the elements before index i (prefix products).
    • Going right to left, keep one variable, suffix, with the product of the elements after index i, and multiply it into answer[i].

    The right-hand products need no second list, because each one is used exactly once, at the moment the backward pass reaches its index. That is what keeps the extra space at O(1): the output list is reused as the storage for the left products.

    On [1, 2, 3, 4] the forward pass leaves answer = [1, 1, 2, 6]. These are the products of nothing, of 1, of 1 * 2 and of 1 * 2 * 3. The backward pass then goes like this:

    ianswer after answer[i] *= suffixsuffix afterwards
    3[1, 1, 2, 6]4
    2[1, 1, 8, 6]12
    1[1, 12, 8, 6]24
    0[24, 12, 8, 6]24

    Step by step

    1. Store the length in n, since both loops need it.
    2. Create answer as [0] * n and set answer[0] to 1. Nothing lies to the left of the first element, and a product of no numbers is 1, the way an empty sum is 0.
    3. Loop forward with range(1, n). Index 0 is already filled.
    4. Extend the prefix product: answer[i] is answer[i - 1] times nums[i - 1]. Each entry reuses the one before it.
    5. Start suffix at 1, for the same reason as the first entry: the last element has nothing to its right.
    6. Loop backward with range(n - 1, -1, -1). The stop value is left out, so a stop of -1 makes 0 the last index visited, and the step of -1 counts down.
    7. Multiply answer[i] by suffix. The entry held the left product; now it holds left times right.
    8. Then multiply suffix by nums[i], so it covers that element when the loop moves one step left. The order matters: if suffix were updated first, answer[i] would include nums[i] itself.
    9. Return answer.

    The solution in Python

    class Solution:
        def productExceptSelf(self, nums: List[int]) -> List[int]:
            n = len(nums)
            answer = [0] * n
            answer[0] = 1
            for i in range(1, n):
                answer[i] = answer[i - 1] * nums[i - 1]
            suffix = 1
            for i in range(n - 1, -1, -1):
                answer[i] *= suffix
                suffix *= nums[i]
            return answer
    

    A few Python details are worth knowing:

    • [0] * n builds a list of n zeros. For numbers this is safe, because integers are immutable and assigning to one slot replaces that slot only.
    • range(n - 1, -1, -1) is the usual way to count down over every index. range(n - 1, 0, -1) would stop one index too early and leave answer[0] without its right-hand product.
    • *= updates a list slot in place: answer[i] *= suffix means answer[i] = answer[i] * suffix.
    • Big numbers are not a problem. Python integers grow as needed, so there is no overflow to guard against. The lesson's constraints keep every product within 32 bits anyway.

    Complexity

    Time: O(n). The method makes one forward pass and one backward pass, and each step does a single multiplication.

    Space: O(1) extra. The only additions beyond the returned list are n, i and suffix. The prefix products live in answer itself.

    Edge cases and common mistakes

    • Zeros. One zero makes every entry zero except the one at the zero's index: [5, 0, 2] gives [0, 10, 0]. Two zeros make everything zero: [0, 0, 3] gives [0, 0, 0]. The two-pass method needs no special case, which a division-based approach would.
    • Two elements. [2, 3] gives [3, 2]: each answer is the other element.
    • Negative numbers. They need no special handling. [-1, 1, 0, -3, 3] gives [0, 0, 9, 0, 0], with the two negative factors in the 9 cancelling out.
    • Updating suffix too early. Swapping the last two lines of the second loop puts nums[i] into its own answer.
    • Starting a product at 0. Both answer[0] and suffix must start at 1. Starting at 0 turns every product into 0.

    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].
    • [5, 0, 2] gives [0, 10, 0].
    • [0, 0] gives [0, 0].
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free