Find products of all locations of an array except its own location

In this algorithm we are asked to find the product of all elements in the array expect the location where the counter is pointing currently.

For example:

  1. If array looks like this 1, 2, 3, 4, 5 where 1 is at location 0, 2 is at location 1 and so on.
  2. The the product array will look like: 120, 60, 40, 30, 25.
  3. 120 is the product of 2 * 3, * 4 * 5
  4. 60 is the product of 1 * 3 * 4 * 5 and so on.


Approach:

  1. We will first find the product of all elements by going through the entire array. Then at each location we will divide the value found at that location.
  2. For example: 120 is product of 1 * 2 * 3 * 4 * 5
  3. For location 0 we will do 120/1 so at location 0 we have 120.
  4. For location 1 we will do 120/2 so at location 1 we will have 60
  5. For location 2 we will do 120/3 so at location 1 we will have 40


Algorithm:
  1. Initialize a variable product = 1; 
  2. Initialize a variable i at 0 
  3. Multiply product with a[i] and increment i by 1. 
  4. Repeat step 3 till end of array a is reached. 
  5. Initialize a variable i at 0 
  6. Do product/a[i] and increment i by 1. Store the result in a array location. 
  7.  Repeat step 6 till end of array a is reached.

Implementation:
 void arr(int a[MAX])
{
 int product = 1;

 for(int i=0;i < MAX;i++)
   product = product * a[i];

 for(int i=0;i < MAX;i++)
   a[i] = product/a[i];
}

int main()
{
 int a[4] = {1,2,3,4};

 for(int i=0;i < 4;i++)
   std::cout <<  a[i] <<  "\t";
 arr(a);

 std::cout <<  std::endl;

 for(int i=0;i < 4;i++)
   std::cout <<  a[i] <<  "\t";

 getch();
 return 0;
}

Complexity:
O(n) for the time complexity since we iterate through the entire array twice.
O(1) for space complexity.

You might also like:
Find White Spaces in Character Array
Find a character in the String
Number is prime or not
Finding Absolute Value
Notes on Sorting and Searching Algorithms
Common String Functions
Reverse a String
Find a cycle in the Linked List
Find a binomial co-efficient
Remove duplicates from the array
Telephonic phone technical interview questions - Part 2
Counting sort algorithm
B-Tree

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...