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.
Examples
Example 1
`nums = [1, 2, 3, 4]``[24, 12, 8, 6]`Example 2
`nums = [-1, 1, 0, -3, 3]``[0, 0, 9, 0, 0]`Example 3
`nums = [2, 3]``[3, 2]`Constraints
2 <= nums.length <= 10^5-30 <= nums[i] <= 30- The input is generated such that
answer[i]is guaranteed to fit in a 32-bit integer.
Hints
Hint 1
"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.
Hint 2
"Everything except me" splits into a left part and a right part: prefix and suffix products.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
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.
Alternative. Two separate prefix and suffix arrays: easier to explain, but O(n) extra space.
Complexity
- Time
- O(n)
O(n) time. O(1) extra space besides the output array.
- Space
- O(1)
Code
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]
}
}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.
Interview script
"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."
Source: LeetCode 238: Product of Array Except Self Source: JLS 17, 15.17.1: Multiplication operator
Sources (2)
- LeetCode 238: Product of Array Except Selfleetcode.com
- JLS 17, 15.17.1: Multiplication operatordocs.oracle.com