Start learning free

LESSON 36 OF 314 · PARTIAL SUMS #1

Product of Array Except Self in JavaScript: 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

    JAVASCRIPT · PARTIAL SUMS #1

    Product Of Array Except Self in JavaScript, explained

    Problem overview

    The method productExceptSelf(nums) takes an array of integers and returns an array 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 statement asks for O(n) time with O(1) extra space, where the returned array doesn't count.

    For nums = [1, 2, 3, 4] the answer is [24, 12, 8, 6]: answer[0] is 2 * 3 * 4, answer[1] 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 0 is 0, and only answer[2] leaves it out.

    Approach: products from the left, then from the right

    The obvious idea multiplies all the elements and divides by nums[i]. That is forbidden, and it also breaks as soon as the array contains a 0. Another idea computes each answer with an inner loop over the other elements, which costs O(n²).

    The faster idea splits every answer into two halves: the product of everything to the left of i times the product of everything to the right of i. Both halves can be built with running products, so the whole thing takes two passes.

    • Left to right: store in answer[i] the product of the elements before index i. Each entry reuses the previous one: answer[i] = answer[i - 1] * nums[i - 1]. These are prefix products.
    • Right to left: keep one variable, suffix, holding the product of the elements after the current index. Multiply it into answer[i], then fold nums[i] into it for the next step.

    The right side needs only a single variable because each suffix product is used exactly once, at the moment the loop passes over its index. That is why the extra space stays O(1), since the only array is the one we return.

    On [1, 2, 3, 4] the first pass leaves [1, 1, 2, 6] in answer. The second pass runs from index 3 down to 0:

    ianswer after the stepsuffix after the step
    31,1,2,64
    21,1,8,612
    11,12,8,624
    024,12,8,624

    The zero example shows why the split works even when the array contains 0. On [-1, 1, 0, -3, 3] the first pass leaves [1, -1, -1, 0, 0]. The suffix value used at each index, from left to right, is [0, 0, -9, 3, 1]. Multiplying them index by index gives [0, 0, 9, 0, 0]. At index 2 both halves are non-zero (-1 on the left, -9 on the right), and everywhere else one half already contains the zero.

    Step by step

    1. Store the length in a const named n, because both loops need it.
    2. Create answer as new Array(n).fill(0). A bare new Array(n) has empty slots, so fill gives it real values to overwrite. Then set answer[0] = 1: nothing lies to the left of the first element, and the product of no numbers is 1.
    3. Loop from index 1 up to n - 1. Index 0 is already done.
    4. Extend the left product. The product left of i is the product left of i - 1 times nums[i - 1].
    5. Declare suffix with let, starting at 1, because it changes on every step and the last element has nothing to its right.
    6. Loop from n - 1 down to 0.
    7. Combine the halves with answer[i] *= suffix. The left product is already stored, and suffix is the right product.
    8. Update suffix after that with suffix *= nums[i]. The order matters: doing it first would put nums[i] into its own answer.
    9. Return answer.

    The solution in JavaScript

    class Solution {
        productExceptSelf(nums) {
            const n = nums.length;
            const answer = new Array(n).fill(0);
            answer[0] = 1;
            for (let i = 1; i < n; i++) {
                answer[i] = answer[i - 1] * nums[i - 1];
            }
            let suffix = 1;
            for (let i = n - 1; i >= 0; i--) {
                answer[i] *= suffix;
                suffix *= nums[i];
            }
            return answer;
        }
    }
    

    Some JavaScript details worth knowing:

    • const does not freeze the array. answer is declared with const, which only stops you from reassigning the variable. Its elements can still change, which is what both loops do. suffix holds a number that must change, so it uses let.
    • *= is shorthand. answer[i] *= suffix means answer[i] = answer[i] * suffix.
    • Negative zero. JavaScript numbers are doubles, and a double has both 0 and -0. Multiplying 0 by a negative number gives -0. For [-1, 1, 0, -3, 3] the function returns an array that console.log prints as [ -0, 0, 9, -0, 0 ]. Comparisons treat the two zeros as equal: r[0] === 0 is true, and String(r[0]) gives "0". Only Object.is(r[0], 0) tells them apart, and it returns false here. You don't need to fix anything for this problem.

    Complexity

    Time: O(n). The function makes two passes over the array, and each iteration does a constant amount of work.

    Space: O(1) extra. Besides the returned array, the function keeps only n, suffix and the loop counters.

    Edge cases and common mistakes

    • Using division. Dividing the total product by nums[i] fails for zeros, since dividing by 0 gives Infinity or NaN in JavaScript. It's also against the rules.
    • One zero or several. With [0, 4, 5] the function returns [20, 0, 0]: only the zero's own position gets a non-zero value. With [0, 0] every answer is 0.
    • Updating suffix too early. If suffix *= nums[i] runs before answer[i] *= suffix, each answer wrongly includes nums[i].
    • Starting suffix or answer[0] at 0. Both must start at 1, the identity for multiplication. Starting at 0 turns everything into 0.
    • Forgetting fill. new Array(n) alone creates empty slots, so the loop could not rely on them.
    • Off-by-one loop bounds. The first loop starts at 1 because it reads answer[i - 1]. The second must include index 0, so it uses i >= 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].
    • [0, 4, 5] gives [20, 0, 0].
    • [5, -2] gives [-2, 5].
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free