A Product Array Puzzle in C++?

C++Server Side ProgrammingProgramming

Here we will see one interesting problem related to array. There is an array with n elements. We have to create another array of n elements. But the i-th position of second array will hold the product of all elements of the first array except the i-th element. And one constraint is that we cannot use the division operator in this problem.

If we can use the division, operation, we can easily solve this problem, by getting the product of all elements, then divide i-th element of first array and store it into i-th place of the second array.

Here we are solving this by creating two separate array. the left and right. the left[i] will hold product of all elements on left of array[i] excluding array[i], and right[i] will hold product of all elements on the right of arr[i] except arr[i]. This solution will take O(n) time. But it will take additional space.

Algorithm

productArray(arr, n)

begin
   define two arrays left and right of size n
   define an array called res of size n
   the first element of left and last element of right is set as 1
   for i in range 1 to n, do
      left[i] = left[i-1] * arr[i-1]
   done
   for i in range n-1 down to 1, do
      right[i] = right[i+1] * arr[i+1]
   done
   for i in range 1 to n, do
      res[i] = left[i] * right[i];
   done
   return res
end

Example

 Live Demo

#include<iostream>
using namespace std;
void printArray(int arr[], int n) {
   for(int i = 0; i<n; i++) {
      cout << arr[i] << " ";
   }
   cout << endl;
}
void productArray(int arr[], int product[], int n) {
   //create left right array
   int *left = new int[sizeof(int)*n];
   int *right = new int[sizeof(int)*n];
   //set the first element of left[] and last element of right[] as 1
   left[0] = right[n-1] = 1;
   for(int i = 1; i<n; i++) {
      left[i] = left[i-1] * arr[i-1];
   }
   for(int i = n-2; i>=0; i--) {
      right[i] = right[i+1] * arr[i+1];
   }
   //get product array using left and right array
   for(int i = 0; i<n; i++) {
      product[i] = left[i] * right[i];
   }
}
main() {
   int myArr[7] = {5, 4, 7, 6, 9, 2, 3};
   int resArr[7];
   cout << "Initial Array: ";
   printArray(myArr, 7);
   productArray(myArr, resArr, 7);
   cout << "Final Array: ";
   printArray(resArr, 7);
}

Output

Initial Array: 5 4 7 6 9 2 3
Final Array: 9072 11340 6480 7560 5040 22680 15120
raja
Updated on 30-Jul-2019 22:30:26

Advertisements