LeetCode 75
Product of Array Except Self
- Problem
- LC 238
- Topic
- Array / String
- File
- official75_LC238ProductOfArrayExceptSelf.java
- Path
- pkg5leetcode/official75/official75_LC238ProductOfArrayExceptSelf.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC238ProductOfArrayExceptSelf.java
- Approach
- Prefix then suffix pass without division.
- Complexity
- Time O(n), Space O(1) extra
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Product of Array Except Self | LC 2385 * APPROACH: Prefix then suffix pass without division.6 * COMPLEXITY: Time O(n), Space O(1) extra7 */8public class official75_LC238ProductOfArrayExceptSelf {9 static int[] productExceptSelf(int[] nums) {10 int n = nums.length;11 int[] res = new int[n];12 res[0] = 1;13 for (int i = 1; i < n; i++) res[i] = res[i - 1] * nums[i - 1];14 int suffix = 1;15 for (int i = n - 1; i >= 0; i--) {16 res[i] *= suffix;17 suffix *= nums[i];18 }19 return res;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}