From 4a0ce642900c2667df7b25cf43bf280c4e8c6a93 Mon Sep 17 00:00:00 2001 From: s50600822 Date: Sat, 25 Nov 2023 04:16:33 +1100 Subject: [PATCH] https://leetcode.com/problems/product-of-array-except-self/ --- .../Solution.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 interview_prep/algorithm/java/ide_handicapped/product_of_array_except_self/Solution.java diff --git a/interview_prep/algorithm/java/ide_handicapped/product_of_array_except_self/Solution.java b/interview_prep/algorithm/java/ide_handicapped/product_of_array_except_self/Solution.java new file mode 100644 index 0000000..47e212a --- /dev/null +++ b/interview_prep/algorithm/java/ide_handicapped/product_of_array_except_self/Solution.java @@ -0,0 +1,57 @@ +import java.util.Arrays; + +class Solution { + /** + * 2n + */ + public int[] productExceptSelf(int[] nums) { + int[] prefixProduct = new int[nums.length]; + prefixProduct[0] = 1; + for (int i = 1; i < nums.length; i++) { + prefixProduct[i] = prefixProduct[i-1] * nums[i-1]; + } + + int suffixProduct = 1; + for (int i = nums.length-1; i >= 0; i--) { + prefixProduct[i] = prefixProduct[i] * suffixProduct; + suffixProduct = suffixProduct * nums[i]; + } + + return prefixProduct; + } + + /** + * n^2 + */ + public int[] productExceptSelfNaive(int[] nums) { + + int[] res = new int[nums.length]; + Arrays.fill(res, 1); + for(int i =0; i< nums.length; i++){ + for(int j = 0; j < nums.length; j++){ + if(i!=j){ + res[j] = res[j] * nums[i]; + } + } + } + return res; + } + public static void main(String[] args) { + //https://leetcode.com/problems/product-of-array-except-self/ + Solution self = new Solution();// pretend to be python :v + assert Arrays.equals( + self.productExceptSelf(new int[]{1,2,3,4}), + new int[]{24,12,8,6} + ); + + assert Arrays.equals( + self.productExceptSelf(new int[]{-1,1,0,-3,3}), + new int[]{0,0,9,0,0} + ); + + assert Arrays.equals( + self.productExceptSelf(new int[]{2,3,4,5}), + new int[]{60,40, 30,24} + ); + } +} \ No newline at end of file