DSA and coding Level 2 This level · 3 of 30
Medium dsa arrays

Product of Array Except Self

The 30 second answer

For each index the answer is the product of everything to its left times everything to its right. I fill the output with left products in one pass, then walk back from the right with a running right product and multiply it in. No division, so zeros are not a problem, and apart from the output it is constant extra space.

Could you say this in an interview?

Problem Return an array where each position holds the product of all other elements, without using division and in linear time. Original: LeetCode 238: Product of Array Except Self.

Understanding the prompt "Without division" rules out "total product divided by nums[i]", which would also fail on zeros. The original guarantees the products fit in an int.

Pattern recognition "Everything except me" splits into a left part and a right part: prefix and suffix products.

Brute force For each i, multiply all the others: O(n²).

Optimal In the first pass, out[i] = product of nums[0..i-1]. In the second pass, go right to left with right = product of nums[i+1..] and set out[i] *= right.

Alternatives Two separate prefix and suffix arrays: easier to explain, but O(n) extra space.

Java solution

import java.util.Arrays;

public class ProductExceptSelf {
    static int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        var out = new int[n];
        out[0] = 1;
        for (int i = 1; i < n; i++) out[i] = out[i - 1] * nums[i - 1];
        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            out[i] *= right;
            right *= nums[i];
        }
        return out;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(productExceptSelf(new int[] {1, 2, 3, 4})));      // [24, 12, 8, 6]
        System.out.println(Arrays.toString(productExceptSelf(new int[] {-1, 1, 0, -3, 3}))); // [0, 0, 9, 0, 0]
        System.out.println(Arrays.toString(productExceptSelf(new int[] {2, 3})));            // [3, 2]
    }
}

Complexity O(n) time. O(1) extra space besides the output array.

Edge cases

  • One zero: only that position is non-zero.
  • Two zeros: everything is 0.
  • Negative values.
  • Length 2.

Follow-ups

  • Products that don't fit in an int: use long, or ask about modulo arithmetic.
  • Explain why the division approach breaks on zeros.

Tests [1,2,3,4] returns [24,12,8,6]. [-1,1,0,-3,3] returns [0,0,9,0,0]. [2,3] returns [3,2].

How to say it in the interview "Each answer is the left product times the right product. I write left products into the output, then sweep from the right with one running variable. No division, O(n) time, constant extra space."

Sources (2)
  1. LeetCode 238: Product of Array Except Selfleetcode.com
  2. JLS 17, 15.17.1: Multiplication operatordocs.oracle.com
Previous
Next