16. Product array puzzle
16. Product array puzzle
\Problem link :- click here
package program;
public class Searching__16
{
/*
Given an array arr[] of size n, construct a product array p[] of same size n
such that p[i] is equal to the products of all the elements of arr[] except arr[i]
arr[] ={10, 3, 5, 6, 2}
output : {180, 600, 360, 300, 900}
We will take two arrays left array and a right array
left array will have the product of the elements to the left of that element
similarly right array
and we will store the p[] with the product of all elements except itself
*/
static int[] productExceptSelf(int arr[], int n)
{
int left[] = new int[n];
int right[] = new int[n];
//initiating left array
left[0] = 1;
for(int i=1; i<n; i++)
left[i] = left[i-1] * arr[i-1];
//initiating right array
right[n-1] = 1;
for(int i=n-2; i>=0; i--)
right[i] = right[i+1] * arr[i+1];
//initiating the product array
int product[] = new int[n];
for(int i=0; i<n; i++)
product[i] = left[i] * right[i];
return product;
}
public static void main(String[] args)
{
int arr[] = {10, 3, 5, 6, 2};
int ans[] = productExceptSelf(arr, arr.length);
System.out.println("Product array is : ");
for(int i=0; i<ans.length; i++)
System.out.print(ans[i] + " ");
}
}
Time copmplexity :- O(n)
Space complexity :- O(n)
Comments
Post a Comment