Skip to content

Instantly share code, notes, and snippets.

@deedee47
Last active May 2, 2021 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deedee47/c985bb54f68299436b0729c8c0280147 to your computer and use it in GitHub Desktop.
Save deedee47/c985bb54f68299436b0729c8c0280147 to your computer and use it in GitHub Desktop.
Return a new array consisting of the product of all elements in the array excluding the current index
public int[] getProducts(int[] nums){
if(nums == null) return new int[0];
if(nums.length == 0) return new int[0];
if(nums.length == 1) return new int[]{0};
int[] products = new int[nums.length];
//any number multiplied by 1 is the same number; therefore allProducts cannot be initialized to 0
int allProducts = 1, start = 0, end = nums.length-1, countOfZeros = 0;
while(start<=end){
if(start==end){
if(nums[start] == 0){
countOfZeros++; //ignore 0s in the array, keep a count in case all/some elements are 0;
}
else{
allProducts *= nums[start];
}
}
else{
if(nums[start] == 0){
countOfZeros++;
}
else{
allProducts *= nums[start];
}
if(nums[end] == 0){
countOfZeros++; //ignore 0s in the array, keep a count in case all elements are 0;
}
else{
allProducts *= nums[end];
}
}
start++; end--;
}
if (countOfZeros > 1) return products; //product of any other number including a 0 still results in 0
// only countOfZeros = 1 can result in the index having a product
for(int index = 0; index < nums.length; index++){
products[index] = (countOfZeros == 1) ?
(nums[index] == 0) ? allProducts : 0
: allProducts/nums[index];
}
return products;
}
@deedee47
Copy link
Author

deedee47 commented May 2, 2021

Hi @meekg33k, wow, the cases really run deep.

Based on the way I implemented the solution, I assumed that once a 0 is present, it makes the product 0 as well. I have considered a different approach based on the case you provided. if there's only one 0 present, then it can have a product otherwise, everything else is 0.

Thanks for the insight.
It is really interesting to participate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment