educative.io

Educative

The solution can be simpler when we’re allowed to use division

The problem statement dose not forbid us from using division as in leet code, the solution should be way simpler, just calculate product of all numbers and do a division in result array. Just need 2 extra flags to check how many 0s are there in the array, if there’re more than 1, result array should be filled with 0s. If there’s one 0, the only non 0 value in result array is at index of 0.

That’s what I wrote first :slight_smile:

    class ProductArray  
{  
  public static int[] findProduct(int arr[])  
  {    
    int [] result = new int[arr.length];

    int mult = 1;
    int zeroIndex = -1;
    for(int i = 0; i < arr.length; i++) {
      if(arr[i] == 0) {
        if(zeroIndex >= 0) {
          return result;
        }

        zeroIndex = i;
      } else {
        mult *= arr[i];
      }
    }

    if (zeroIndex >= 0) {
      result[zeroIndex] = mult;
      return result;
    }

    for(int i = 0; i< arr.length; i++) {
      result[i] = mult / arr[i];
    }

    return result; 
   } 
}