|
| 1 | +// link: https://leetcode.com/problems/product-of-array-except-self/submissions/1831301674/ |
| 2 | +// difficulty: Medium |
| 3 | +class Solution1 { |
| 4 | + // Problem: |
| 5 | + // * return: array where answer[i] = product of all elements except nums[i] |
| 6 | + // Solution: |
| 7 | + // * Time Complexity: O(N) |
| 8 | + // * Space Complexity: O(N) |
| 9 | + public int[] productExceptSelf(int[] nums) { |
| 10 | + int n = nums.length; |
| 11 | + |
| 12 | + // prefixProds[i] = prod of all elements upto i (exclusive) |
| 13 | + int[] prefixProds = new int[n]; |
| 14 | + for(int i = 0; i < n; i++) { |
| 15 | + if(i == 0) { |
| 16 | + prefixProds[i] = 1; |
| 17 | + continue; |
| 18 | + } |
| 19 | + |
| 20 | + prefixProds[i] = prefixProds[i-1] * nums[i-1]; |
| 21 | + } |
| 22 | + |
| 23 | + // suffixProds[i] = prod of all elements from end to i (exclusive) |
| 24 | + int[] suffixProds = new int[n]; |
| 25 | + for(int i = n - 1; i >= 0; i--) { |
| 26 | + if(i == n - 1) { |
| 27 | + suffixProds[i] = 1; |
| 28 | + continue; |
| 29 | + } |
| 30 | + |
| 31 | + suffixProds[i] = suffixProds[i+1] * nums[i+1]; |
| 32 | + } |
| 33 | + |
| 34 | + // multiply prefix and suffix prods to find answers |
| 35 | + int[] answers = new int[n]; |
| 36 | + for(int i = 0; i< n;i++) { |
| 37 | + answers[i] = prefixProds[i] * suffixProds[i]; |
| 38 | + } |
| 39 | + |
| 40 | + return answers; |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// uses only 1 array whereas solution 1 uses 3 |
| 45 | +class Solution2 { |
| 46 | + // Problem: |
| 47 | + // * return: array where answer[i] = product of all elements except nums[i] |
| 48 | + // Solution: |
| 49 | + // * Time Complexity: O(N) |
| 50 | + // * Space Complexity: O(N) |
| 51 | + public int[] productExceptSelf(int[] nums) { |
| 52 | + int n = nums.length; |
| 53 | + |
| 54 | + // prefixProds[i] = prod of all elements upto i (exclusive) |
| 55 | + int[] answers = new int[n]; |
| 56 | + for(int i = 0; i < n; i++) { |
| 57 | + if(i == 0) { |
| 58 | + answers[i] = 1; |
| 59 | + continue; |
| 60 | + } |
| 61 | + |
| 62 | + answers[i] = answers[i-1] * nums[i-1]; |
| 63 | + } |
| 64 | + |
| 65 | + // use a single variable for suffix product |
| 66 | + int suffixProd = 1; |
| 67 | + for(int i = n - 2; i >= 0; i--) { |
| 68 | + suffixProd *= nums[i+1]; |
| 69 | + answers[i] *= suffixProd; |
| 70 | + } |
| 71 | + |
| 72 | + return answers; |
| 73 | + } |
| 74 | +} |
| 75 | + |
0 commit comments