# 238. Product of Array Except Self

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]`.

{% hint style="info" %}
Write an algorithm that runs in `O(n)` time and without using the division operation.
{% endhint %}

***

## Intuition

* We need to find the product of all elements before and after the current element.
* We can iterate from end to store the product of all elements till now excluding the self.
  * Then iterate from the start to get the product of all elements till now excluding the self.

## Approach

* Iterate from the end to store the product till now excluding the self in the `answer` array.
  * Iterate from the start to get the product of all elements till now excluding the self.
  * the current element is product of `answer[i] = productTillNowFront * answer[i];`

## Complexity

| Space Complexity | Time Complexity |
| ---------------- | --------------- |
| $$\text{O}(n)$$  | $$\text{O}(n)$$ |

* We iterate over the array twice.
* Extra space is used to store the answer, but as per the question its to be ignored

## Code

```java
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] answer = new int[nums.length];

        // calculate the product till now from the end
        answer[nums.length - 1] = 1;
        int productTillNow = nums[nums.length - 1];
        
        for (int i = nums.length - 2; i >= 0; --i) {
            answer[i] = productTillNow;
            productTillNow *= nums[i];
        }

        // calculate the product till now from the start
        int productTillNowFront = 1;
        for (int i = 0; i < nums.length; ++i) {
            int temp = nums[i];
            answer[i] = productTillNowFront * answer[i];

            productTillNowFront *= temp;
        }
        
        return answer;
    }
}
```


---

# 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://private-26.gitbook.io/notes/coding/medium/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.
