Start learning free

LESSON 314 OF 667 · PARTIAL SUMS #1

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

Practice O(n) Read the full explanation

You get a vector of integers nums.

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

STEP 1 OF 9
    Ctrl + Enter to check

    C++ · PARTIAL SUMS #1

    Product Of Array Except Self in C++, explained

    Problem overview

    The method productExceptSelf takes a vector<int> named nums and returns a vector answer of the same length, where answer[i] is the product of every element of nums except nums[i]. Division is not allowed. The statement also asks for O(n) time and O(1) extra space, not counting the returned vector.

    For [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 0 is 0, and only the entry at the 0's own position leaves it out.

    Approach: left products times right products

    The obvious fix is to multiply everything and divide by nums[i]. That is forbidden, and it also breaks on zeros. The brute-force alternative multiplies all the other elements for each index, which costs O(n²).

    The faster idea splits each answer into two parts. Everything except nums[i] is the product of the elements to the left of i times the product of the elements to the right of i. Both sides can be built with running products, one pass each:

    • Going left to right, keep the product of everything seen so far. Store it in answer[i] before including nums[i].
    • Going right to left, keep the same kind of running product in a single variable, and multiply it into answer[i].

    The returned vector holds the left products, so no second vector is needed. That is how the extra space stays O(1).

    Step by step

    1. Store the length in an int named n. Both loops use it.
    2. Create answer as a vector<int> of size n filled with 0, then set answer[0] to 1. Nothing lies to the left of the first element, and a product of no numbers is 1.
    3. Loop from 1 to n - 1. Index 0 is already done.
    4. Set answer[i] to answer[i - 1] * nums[i - 1]. The product left of i is the product left of i - 1, times the element at i - 1. These are prefix products.
    5. Create suffix as an int starting at 1. It will hold the product of everything to the right of the current index.
    6. Loop from n - 1 down to 0. The last element has nothing on its right, which is why suffix starts at 1.
    7. Multiply answer[i] by suffix. Now it holds left product times right product.
    8. Multiply suffix by nums[i], after the previous line. Doing it first would put nums[i] into its own answer.
    9. Return answer.

    The solution in C++

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size();
            vector<int> answer(n, 0);
            answer[0] = 1;
            for (int i = 1; i < n; i++) {
                answer[i] = answer[i - 1] * nums[i - 1];
            }
            int suffix = 1;
            for (int i = n - 1; i >= 0; i--) {
                answer[i] *= suffix;
                suffix *= nums[i];
            }
            return answer;
        }
    };
    

    The C++ details worth knowing:

    • vector<int>(n, 0) builds a vector with n elements, all 0. This matters because answer[i] is assigned by index, and indexing a vector doesn't make room: answer[0] = 1 on an empty vector would be undefined behaviour.
    • nums.size() is unsigned. The solution copies it into an int, so the loop counter i can safely go down to 0 and stop at i >= 0. With an unsigned counter, i >= 0 is always true and the loop never ends. Likewise size() - 1 on an empty vector wraps to 18446744073709551615. The constraints guarantee at least two elements, so answer[0] = 1 is safe here.
    • vector<int>& nums is a reference, so the input isn't copied. The solution only reads it.
    • *= updates the element in place, so answer[i] *= suffix is answer[i] = answer[i] * suffix.

    Tracing the example

    For nums = [1, 2, 3, 4], the first loop leaves answer = [1, 1, 2, 6]: the product of everything to the left of each position. The second loop then runs right to left:

    ianswer[i] after *= suffixsuffix after *= nums[i]
    364
    2812
    11224
    02424

    The result is [24, 12, 8, 6].

    Why the two passes cover everything

    Take the position i = 2 in [1, 2, 3, 4]. The left pass stored 1 * 2 = 2 there. By the time the right-to-left loop reaches index 2, suffix has absorbed nums[3] and equals 4. The product 2 * 4 = 8 contains every element except nums[2], and no element appears twice. The same argument works at every index, because the left pass never looks past i - 1 and suffix never includes anything at or left of i when it is used.

    This is also why the lesson reuses the output vector as the storage for the left products. A common first version keeps three vectors, left, right and answer, which also runs in O(n) time but uses O(n) extra space. Replacing the whole right vector with one number works because each right-side product is needed exactly once, at the moment the loop visits that index.

    Complexity

    Time is O(n): two loops of n steps each, with one or two multiplications per step. Extra space is O(1): the only additions besides the returned vector are n, suffix and the loop counter.

    Edge cases and common mistakes

    • Zeros. No division means zeros need no special handling. With [0, 0, 2] the result is [0, 0, 0], and with [5, 0, 4] it is [0, 20, 0]: only the entry at the single 0 is non-zero.
    • Two elements. [2, 3] gives [3, 2]: each entry is the other element.
    • Wrong update order. Updating suffix before answer[i] multiplies nums[i] into its own answer.
    • Starting the first loop at 0. It would read answer[-1] and nums[-1], which is out of bounds and undefined behaviour in C++.
    • Overflow. Signed int overflow is undefined behaviour. The statement guarantees that every prefix product, suffix product and answer fits in 32 bits, so this solution is safe on valid input.
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free