For example:
- If array looks like this 1, 2, 3, 4, 5 where 1 is at location 0, 2 is at location 1 and so on.
- The the product array will look like: 120, 60, 40, 30, 25.
- 120 is the product of 2 * 3, * 4 * 5
- 60 is the product of 1 * 3 * 4 * 5 and so on.
Approach:
- 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.
- For example: 120 is product of 1 * 2 * 3 * 4 * 5
- For location 0 we will do 120/1 so at location 0 we have 120.
- For location 1 we will do 120/2 so at location 1 we will have 60
- For location 2 we will do 120/3 so at location 1 we will have 40
Algorithm:
- Initialize a variable product = 1;
- Initialize a variable i at 0
- Multiply product with a[i] and increment i by 1.
- Repeat step 3 till end of array a is reached.
- Initialize a variable i at 0
- Do product/a[i] and increment i by 1. Store the result in a array location.
- 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