Find product of all numbers in an array except self

It is a commonly asked interview question during onsite or phone interview. So the question is given an array, how will you find a product at all locations of an array without its own location.

Background:
If you are given an array: 1,2,3,4 then you are required to provide a product of all locations expect self. In this case, your response will be a,b,c,d. a will be calculated by taking product of b,c, and d. b will be calculated by taking product of a,c,d. Similarly here are other calculations:
c = a * b * d
d = a * b * c.

Brute force approach is iterate through all the locations and calculate the product skipping its own location. It can be implemented using 2 for loops and its complexity will be O(N*N). But there is a better way to do it and its mentioned in following algorithm. Idea of the algo is:

  1. calculate the product of all locations before hand. 
  2. Iterate through the array and divide the product with the value provided at its location.

Algorithm:

  1. First find the product of the all the values in the array. 
  2. If product is not equal to zero then proceed to step 3 or else end. 
  3. At every array location, divide the product with the number at array location. That will return the product of all locations of array expect self. 

Implementation: 
public class Test  {
    static int a[] = {1,2,3,4};

    public static void calculateProductExpectSelf() {
        int product = 1;
        for(int i=0; i<a.length; i++) {
            product *= a[i];
        }
        if(product != 0) {
           int b[] = new int[4];
            for(int i=0;i<a.length;i++) {
               if(a[i] != 0) {
                   b[i] = product/a[i];
                   System.out.println("\t" + b[i]);
               }
            }
        } else {
                  System.out.println("Product is zero"]);
     }

    public static void main(String args[]) {
        calculateProductExpectSelf();
    }
}


Dry Run: 
array = a[] = {1,2,3,4}
Product = 1*2*3*4 = 24
  1. In first iteration, the program will print: 24/1 = 24.
  2. In second iteration, the program will print: 24/2 = 12.
  3. In third iteration, the program will print: 24/3 = 8.
  4. In fourth iteration, the program will print: 24/4 = 6.
Complexity:
O(N)

No comments:

Post a Comment

NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...