|
| 1 | +/* |
| 2 | +input : array of integer |
| 3 | +output : array of integer that each element |
| 4 | + is product of all the elements except itself |
| 5 | +constraint |
| 6 | +1) is the result of product also in range of integer? |
| 7 | +yes product of nums is guaranteed to fit 32-bit int |
| 8 | +2) how about zero? |
| 9 | +doesn't matter if the prduct result is zero |
| 10 | +3) is input array non-empty? |
| 11 | +yes. length of array is in range [2, 10^5] |
| 12 | +
|
| 13 | +solution1) brute force |
| 14 | +
|
| 15 | +calc all the product except current index element |
| 16 | +
|
| 17 | +tc : O(n^2) sc : O(n) << for the result. when n is the length of input array |
| 18 | +
|
| 19 | +solution 2) better? |
| 20 | +ds : array |
| 21 | +algo : hmmm we can reuse the product using prefix sum |
| 22 | +
|
| 23 | +1) get prefix sum from left to right and vice versa : 2-O(n) loop + 2-O(n) space |
| 24 | +2) for i = 0 to n-1 when n is the length of input |
| 25 | + get product of leftPrfex[i-1] * rightPrefix[i+1] |
| 26 | + // edge : i == 0, i == n-1 |
| 27 | +
|
| 28 | +tc : O(n) sc : O(n) |
| 29 | +
|
| 30 | +solution 3) optimal? |
| 31 | +can we reduce space? |
| 32 | +1) product of all elements. divide by current element. |
| 33 | +
|
| 34 | + > edge : what if current element is zero? |
| 35 | + 2) if there exists only one zero: |
| 36 | + all the elements except zero index will be zero |
| 37 | + 3) if there exist multiple zeros: |
| 38 | + all the elements are zero |
| 39 | + 4) if there is no zero |
| 40 | + do 1) |
| 41 | + */ |
| 42 | +class Solution { |
| 43 | + public int[] productExceptSelf(int[] nums) { |
| 44 | + int n = nums.length, product = 1, zeroCount = 0; |
| 45 | + for(int num : nums) { |
| 46 | + if(num == 0) { |
| 47 | + zeroCount ++; |
| 48 | + if(zeroCount > 1) break; |
| 49 | + } else { |
| 50 | + product *= num; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + int[] answer = new int[n]; |
| 55 | + if(zeroCount > 1) { |
| 56 | + return answer; |
| 57 | + } else if (zeroCount == 1) { |
| 58 | + for(int i = 0; i < n; i++) { |
| 59 | + if(nums[i] != 0) { |
| 60 | + answer[i] = 0; |
| 61 | + continue; |
| 62 | + } |
| 63 | + answer[i] = product; |
| 64 | + } |
| 65 | + } else { |
| 66 | + for(int i = 0; i < n; i++) { |
| 67 | + answer[i] = product / nums[i]; |
| 68 | + } |
| 69 | + } |
| 70 | + return answer; |
| 71 | + } |
| 72 | +} |
0 commit comments