Blind 75

Product of Array Except Self

Problem
LC 238
Category
Array
File
blind75_LC238ProductOfArrayExceptSelf.java
Path
pkg5leetcode/blind75/blind75_LC238ProductOfArrayExceptSelf.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC238ProductOfArrayExceptSelf.java
Approach
Prefix and suffix products without division.
Complexity
Time O(n), Space O(1) excluding output

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC238ProductOfArrayExceptSelf.java
1package pkg5leetcode.blind75;2 3/*4 * Product of Array Except Self | LC 2385 * APPROACH: Prefix and suffix products without division.6 * COMPLEXITY: Time O(n), Space O(1) excluding output7 */8public class blind75_LC238ProductOfArrayExceptSelf {9    static int[] productExceptSelf(int[] nums) {10        int n = nums.length;11        int[] out = new int[n];12        out[0] = 1;13        for (int i = 1; i < n; i++) out[i] = out[i - 1] * nums[i - 1];14        int suffix = 1;15        for (int i = n - 1; i >= 0; i--) {16            out[i] *= suffix;17            suffix *= nums[i];18        }19        return out;20    }21 22    public static void main(String[] args) {23        check(java.util.Arrays.equals(productExceptSelf(new int[]{1, 2, 3, 4}), new int[]{24, 12, 8, 6}), "case1");24        check(java.util.Arrays.equals(productExceptSelf(new int[]{-1, 1, 0, -3, 3}), new int[]{0, 0, 9, 0, 0}), "case2");25        System.out.println("all tests passed");26    }27 28    static void check(boolean cond, String name) {29        if (!cond) throw new AssertionError("FAILED: " + name);30        System.out.println("  PASS " + name);31    }32}