Above/Below Product Arrays (Javascript)


  • 0
    J

    General idea is to construct an above and below array containing the product for each respectively. The answer is derived by taking the index that we're at and doing a lookup on both arrays. Runs O(n).

    /**
     * @param {number[]} nums
     * @return {number[]}
     */
    var productExceptSelf = function(nums) {
        const above = [];
        const below = [];
        const res = [];
        let aboveProduct = 1;
        let belowProduct = 1;
        
        for (let i = 0; i < nums.length; i++) {
            below[i] = belowProduct;
            belowProduct = belowProduct * nums[i];
        }
        
        for (let i = nums.length - 1; i >= 0; i--) {
            above[i] = aboveProduct;
            aboveProduct = aboveProduct * nums[i];
        }
        
        for (let i = 0; i < nums.length; i++) {
           res[i] = below[i] * above[i];
        }
        
        return res;
    };

Log in to reply
 

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