# 4. 238. Product of Array Except Self

{% embed url="<https://leetcode.com/problems/product-of-array-except-self/solutions/3660630/product-of-array-except-self-o-n-time-complexity-o-1-space-complexity/>" %}

> Time: O(n) Space: O(1)

```jsx
var productExceptSelf = function(nums) {
    const products = new Array(nums.length).fill(1);

    for (let i = 1; i < nums.length; i++) {
        products[i] = nums[i - 1] * products[i - 1];
    }

    let acc = 1;
    for (let i = nums.length - 1; i >= 0; i--) {
        products[i] = products[i] * acc;
        acc = acc * nums[i]; 
    }

    return products;
};
```

> Time: O(n)
>
> Space: O(n)

```javascript
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var productExceptSelf = function(nums) {
    const left = new Array(nums.length).fill(1);
    const right = new Array(nums.length).fill(1);

    // 1   1   2   6
    // 24   12  4  1

    for (let i = 1; i < nums.length; i++) {
        left[i] = nums[i - 1] * left[i - 1];
    }

    for (let i = nums.length - 2; i >= 0; i--) {
        right[i] = nums[i + 1] * right[i + 1]; 
    }

    const products = [];
    for (let i = 0; i < nums.length; i++) {
        products[i] = left[i] * right[i];
    }

    return products;
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/array/4.-238.-product-of-array-except-self.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
