## DEV Community is a community of 674,199 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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

codingpineapple

### 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
};

``````