Monday, February 27, 2012

Construct Product Array

Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator and in O(n).
Example:
arr[] = {10, 3, 5, 6, 2}
prod[] = {180, 600, 360, 300, 900}

http://www.geeksforgeeks.org/a-product-array-puzzle/

Strategy:
1) Construct a temporary array left[] such that left[i] contains product of all elements on left of arr[i] excluding arr[i].
2) Construct another temporary array right[] such that right[i] contains product of all elements on on right of arr[i] excluding arr[i].
3) To get prod[], multiply left[] and right[].


Code:
#include <stdio.h>
#include <stdlib.h>

void productArray(int arr[], int n)
{
int *left = (int *)malloc(sizeof(int)*n);
int *right = (int *)malloc(sizeof(int)*n);

int *prod = (int *)malloc(sizeof(int)*n);

int i, j;

/* Left most element of left array is always 1 */
left[0] = 1;

/* Rightmost most element of right array is always 1 */
right[n-1] = 1;

for(i = 1; i < n; i++)
  left[i] = arr[i-1]*left[i-1];

for(j = n-2; j >=0; j--)
   right[j] = arr[j+1]*right[j+1];

for (i=0; i<n; i++)
   prod[i]=left[i]*right[i];

for (i=0; i<n; i++)
    printf("%d ", prod[i]);
free(left);
free(right);
free(prod);
return;
}
int main() {
    int arr[] = {10, 3, 5, 6, 2};
    int n=sizeof(arr)/sizeof(arr[0]);
    productArray(arr,n);

   getchar();
    return 0;
}

No comments:

Post a Comment