↻one more pass.
Arrays & hashing · Medium

Product of Array Except Self: the idea to remember.

For every index, return the product of all other values without using division.

Solve on LeetCode ↗

The core insight

Store prefix products in the output, then multiply by a running suffix product.

Why it works

At index i the result combines precisely the elements before i and after i.

The mistake to avoid

Include the current element only after using the running prefix or suffix. Zeros need no special handling.

Time: O(n)Space: O(1) auxiliary, excluding output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int[] productExceptSelf(int[] nums) {
    int[] out = new int[nums.length];
    int prefix = 1;
    for (int i = 0; i < nums.length; i++) {
        out[i] = prefix; // Product strictly before i.
        prefix *= nums[i];
    }
    int suffix = 1;
    for (int i = nums.length - 1; i >= 0; i--) {
        out[i] *= suffix; // Product strictly after i.
        suffix *= nums[i];
    }
    return out;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.