Skip to content

Instantly share code, notes, and snippets.

@Nkwachi-N
Created May 2, 2021 10:07
Show Gist options
  • Save Nkwachi-N/b0962619522f1099c6c5ca99b12451d9 to your computer and use it in GitHub Desktop.
Save Nkwachi-N/b0962619522f1099c6c5ca99b12451d9 to your computer and use it in GitHub Desktop.
public static int[] algoFunc(int[] numArray) {
int totalMultiplication = 1;
for(int num : numArray) {
try{
totalMultiplication = totalMultiplication * num;
}catch (ArithmeticException e){
totalMultiplication = 0;
break;
}
}
int arrayLength = numArray.length;
int[] newArray = new int[arrayLength];
for(int i = 0 ; i < arrayLength ; i++) {
if(numArray[i] == 0) {
int multiplier = 1;
//This comment encloses the short code I could come up with to solve the algorithm but I believe
for(int j = 0 ; j < arrayLength ; j++) {
if(j == i) continue;
try{
multiplier = multiplier * numArray[j];
}catch (ArithmeticException e) {
multiplier = 0;
break;
}
}
//it's madly inefficient when the array does not contain 0.
//Hence my solution.
newArray[i] = multiplier;
continue;
}
try {
newArray[i] = totalMultiplication /numArray[i];
}catch (ArithmeticException e){
newArray[i] = 0;
}
}
return newArray;
}
@meekg33k
Copy link

meekg33k commented May 2, 2021

Hello @Itz-kwaz, thank you for participating in Week 4 of Algorithm Fridays.

Your solution passes all the test cases in terms of correctness. Kudos to you!

However, in terms of time efficiency, your solution uses a nested loop which causes a time complexity of O(N). Do you think we can do better?

All the same, this is a good attempt! Let me know what you think.

@Nkwachi-N
Copy link
Author

Thank you @meekg33k for conducting Algrorithn Fridays.
I currently can't think of any better solution, I'm looking forward to the published solution.
It'll be really informative and interesting to see the best eay to solve this without a nested loop.

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