# 238.Product-of-Array-Except-Self

## 238. Product of Array Except Self

## 题目地址

<https://leetcode.com/problems/product-of-array-except-self/>

## 题目描述

```
Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:
Input:  [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
```

## 代码

### Approach 1: Left + Right Array

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

    int[] answer = new int[length];

    L[0] = 1;
    for (int i = 1; i < length; i++) {
      L[i] = nums[i - 1] * L[i - 1];
    }

    R[length - 1] = 1;
    for (int i = lenght - 2; i >= 0; i--) {
      R[i] = nums[i + 1] * R[i + 1];
    }

    for (int i = 0; i < length; i++) {
      answer[i] = L[i] * R[i];
    }

    return answer;
  }

}
```

### Approach 2: O(1) space approach

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

    answer[0] = 1;
    for (int i = 1; i < length; i++) {
      answer[i] = nums[i - 1] * answer[i - 1];
    }

    int R = 1;
    for (int i = length - 1; i >= 0; i--) {
      answer[i] = answer[i] * R;
      R *= nums[i];
    }

    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://wentao-shao.gitbook.io/leetcode/array/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.
