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:
- calculate the product of all locations before hand.
- Iterate through the array and divide the product with the value provided at its location.
Algorithm:
- First find the product of the all the values in the array.
- If product is not equal to zero then proceed to step 3 or else end.
- 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
Complexity:
- In first iteration, the program will print: 24/1 = 24.
- In second iteration, the program will print: 24/2 = 12.
- In third iteration, the program will print: 24/3 = 8.
- In fourth iteration, the program will print: 24/4 = 6.
O(N)
No comments:
Post a Comment