Prompt:

Given an integer array nums, return an array output where output[i] is the product of all the elements of nums except nums[i].

Each product is guaranteed to fit in a 32-bit integer.

Follow-up: Could you solve it in O(n)O(n) time without using the division operation?

Example 1:

Input: nums = [1,2,4,6]
 
Output: [48,24,12,8]

Example 2:

Input: nums = [-1,0,1,2,3]
 
Output: [0,-6,0,0,0]

Constraints:

  • 2 <= nums.length <= 100,000
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Solution:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) 
    {
        //create prefix array, and add in first element
        vector<int> prefixArray;
        prefixArray.push_back(1);
        for(int i = 1; i <= nums.size(); i++)
        {
            prefixArray.push_back(nums[i-1] * prefixArray[i-1]);
        }
 
        //create the suffix array, have it initialize at size and then have a 1 at the end
        vector<int> suffixArray(nums.size()+1);
        suffixArray[nums.size()] = 1;
        for(int i = nums.size(); i > 0; i--)
        {
            suffixArray[i-1] = suffixArray[i] * nums[i-1];
        }
 
        //create the return array and then multiple the suffix array times prefix array to get the sum without current index
        vector<int> returnArray;
        for(int i = 0; i < nums.size(); i++)
        {
            returnArray.push_back(suffixArray[i+1] * prefixArray[i]);
        }
 
 
        return returnArray;
    }
};
 

Explanation:

This one actually is one of my more favorite ones of the day 11/6/26, basically the way that it works it uses something called a prefix sum idea, and that basically is a really good way for finding out the sum, or in this case, product, of many different sub arrays within of a given array. So you have an array of integers that all describe a change at a given total right.

You then take each one of those, and you set up a secondary array that counts each consequitive change, with an initial value on the front that does not change the overall operation, so a zero for addition or 1 for multiplication. Here is an example

Pasted image 20261106220850.png

So you can see for the prefix we start with 1, and then 1*1=1, and 1*2=2, 2*4=8, 8*6=48, and then we know that the product of all of the values from the first index to the third would then be just prefix[3] right or well nums[0] through nums[i] = prefix[i-1] basically. This is really good for different use cases, and you basically can do things like the difference of values or the division of values here if you want things like sub array sums or products I think.

For this one specifically however we set up the prefix and suffix as you can see, and then we add in the indexes of prefix[i] and suffix[i+1] (since this is shifted by one), and then we have the solution of the product of all items in the array except the self.