DEV Community

loading...

LeetCode 238. Product of Array Except Self (javascript solution)

codingpineapple
・1 min read

Description:

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

var productExceptSelf = function(nums) {
    // Value to increment per each index
    let carry = 1
    // Array to return all the product values
    const output = Array(nums.length).fill(1)
    // Add products to output array starting at the front
    for(let i = 0; i < nums.length;i++){
        output[i]*=carry
        carry*=nums[i]
    }
    // Reset carry
    carry = 1
    // Add products to output array starting at the back
    for(let i = nums.length-1; i >= 0; i--){
        output[i]*=carry
        carry*=nums[i]
    }
    return output
};

Enter fullscreen mode Exit fullscreen mode

Discussion (0)