Code Logo

Product of Array Except Self

Published atDate not available
Easy 0 views
Like0

This one is about reading carefully and then following a clear rule. In Product of Array Except Self, you are trying to work toward the right list by following one clear idea.

Calculate product of array except self A good way to think about it is to first understand what goes in, then what rule you must follow, and finally what shape the answer should have.

For example, if the input is nums = [1,2,3,4], the answer is [24,12,8,6]. Example with input: nums = [1,2,3,4] Another example is nums = [-1,1,0,-3,3], which gives [0,0,9,0,0]. Example with input: nums = [-1,1,0,-3,3]

This is a friendly practice problem, but it still rewards careful reading. The key is understanding the rule clearly and then applying it carefully.

One helpful habit is to say the rule out loud in your own words before you start solving. If you can explain what counts, what changes, and what the final answer should look like, you are already much closer to the right solution.

Example Input & Output

Example 1
Input
nums = [1,2,3,4]
Output
[24,12,8,6]
Explanation

Example with input: nums = [1,2,3,4]

Example 2
Input
nums = [-1,1,0,-3,3]
Output
[0,0,9,0,0]
Explanation

Example with input: nums = [-1,1,0,-3,3]

Example 3
Input
nums = [2,3,4,5]
Output
[60,40,30,24]
Explanation

Example with input: nums = [2,3,4,5]

Algorithm Flow

Recommendation Algorithm Flow for Product of Array Except Self
Recommendation Algorithm Flow for Product of Array Except Self

Best Answers

java
class Solution {
    public Object product_except_self(Object nums) {
        int[] arr = (int[]) nums;
        int n = arr.length;
        int[] result = new int[n];
        java.util.Arrays.fill(result, 1);
        int left = 1;
        for (int i = 0; i < n; i++) {
            result[i] = left;
            left *= arr[i];
        }
        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            result[i] *= right;
            right *= arr[i];
        }
        return result;
    }
}