Start learning free

LESSON 36 OF 314 · PARTIAL SUMS #1

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

    TYPESCRIPT · PARTIAL SUMS #1

    Product Of Array Except Self in TypeScript, explained

    Problem overview

    The method productExceptSelf receives an array of numbers, nums, 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 algorithm must run in O(n) time with O(1) extra space, not counting the returned array.

    For nums = [1, 2, 3, 4] the answer is [24, 12, 8, 6]: answer[0] is 2 * 3 * 4 = 24, answer[1] is 1 * 3 * 4 = 12, and so on. For [-1, 1, 0, -3, 3] the answer is [0, 0, 9, 0, 0], because every product that includes the zero is zero and only answer[2] leaves it out.

    Approach: left products times right products

    The obvious plan multiplies all the elements and divides by nums[i] for each position. It fails twice: division is banned, and a zero in the array makes the total 0, so dividing gives NaN (for [1, 2, 0, 4] the division idea yields [0, 0, NaN, 0] in TypeScript). Multiplying out the other elements for every position works, but costs O(n²).

    The key observation is that "everything except nums[i]" splits into two parts: everything to the left of i and everything to the right. So answer[i] is the product of the left part times the product of the right part. Both parts can be built with running products:

    • The product to the left of i is the product to the left of i - 1, times nums[i - 1]. These are prefix products.
    • The product to the right of i is the product to the right of i + 1, times nums[i + 1]. Walking from the right end, one running variable is enough.

    The first pass stores the prefix products directly in answer, which is why no second array is needed. The second pass walks backwards, multiplying each entry by the running right-hand product.

    On [1, 2, 3, 4] the first pass leaves answer as [1, 1, 2, 6]: the product of nothing is 1, then 1, then 1 * 2, then 1 * 2 * 3. The second pass then goes from the right, and after each index answer and suffix look like this:

    ianswer after the stepsuffix after the step
    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 a const named n. Both loops use it.
    2. Create answer with n zeros and set answer[0] to 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, since index 0 is already set.
    4. Extend the prefix product: answer[i] is answer[i - 1] * nums[i - 1]. After this loop answer[i] holds the product of everything left of i.
    5. Create suffix with let, starting at 1. It will hold the product of everything right of the current index. The last element has nothing on its right, hence 1.
    6. Loop from n - 1 down to 0.
    7. Multiply answer[i] by suffix. The left part is already in answer[i], so now it holds left times right.
    8. Multiply suffix by nums[i], after the previous line. If it came first, answer[i] would include nums[i] itself. Now the suffix is correct for the next index to the left.
    9. Return answer.

    The solution in TypeScript

    class Solution {
        productExceptSelf(nums: number[]): number[] {
            const n = nums.length;
            const answer: number[] = 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 TypeScript details:

    • new Array(n).fill(0) builds an array of n zeros. Without fill, new Array(n) has empty slots, and the annotation number[] would not change that at run time. Types are erased when the code is compiled to JavaScript.
    • const for the array, let for suffix. const answer only means the variable always points at the same array. Its elements can still change. suffix gets a new value on every step, so it needs let.
    • number is a double. The constraints promise that every prefix, suffix and answer fits in 32 bits, so the products are exact. Beyond 2^53 a product would silently lose precision instead of overflowing.
    • *= multiplies a variable by a value and stores the result back, so answer[i] *= suffix is the same as answer[i] = answer[i] * suffix.

    Complexity

    Time: O(n). There are two loops over the array, each doing a constant amount of work per element.

    Space: O(1) extra. The returned array is the output, and the only other storage is n and suffix. Keeping the prefix products in answer itself is what makes this possible.

    Edge cases and common mistakes

    • Zeros. One zero makes every answer 0 except the one at the zero's own index. Two zeros make every answer 0. The two-pass method needs no special case: [0, 0, 2] gives [0, 0, 0], and [2, 0, 3, 4] gives [0, 24, 0, 0].
    • Negative zero. JavaScript numbers have a signed zero. For [-1, 0, 5] the result prints as [0, -5, -0], because the prefix product -1 * 0 is -0. It still compares equal to 0 with ===, but Object.is(answer[2], 0) is false.
    • Updating in the wrong order. Multiplying suffix by nums[i] before using it puts nums[i] into answer[i].
    • Starting the first loop at 0. It would read answer[-1], which is undefined, and the product becomes NaN.
    • Two elements. For [2, 3] the answer is [3, 2]: each answer is the other element.

    Testing

    • nums = [1, 2, 3, 4] gives [24, 12, 8, 6].
    • nums = [-1, 1, 0, -3, 3] gives [0, 0, 9, 0, 0].
    • nums = [2, 3] gives [3, 2].
    • nums = [5, 0, 2] gives [0, 10, 0].
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free