Sharing my C++ solution in O(n) and with constant space complexity.


  • 3
    R
    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            vector<int> products(nums.size(), 1);
            for (int i = 1; i < nums.size(); ++i){
                products[i] = nums[i-1]*products[i-1];
            }
            int preProduct = 1;
            for (int i = nums.size()-1; i >= 0; --i){
                products[i] = products[i]*preProduct;
                preProduct *= nums[i];
            }
            return products;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.