# Product of non-repeating (distinct) elements in an Array in C++

C++Server Side ProgrammingProgramming

We are given with an array of repeating or duplicate elements and the task is to find the product of all those elements which are non-repeating or distinct in the given array and display the results.

## Example

Input-: arr[] = {2, 1, 1, 2, 3, 4, 5, 5 }
Output-: 120
Explanation-: Since 1, 2 and 5 are repeating more than once so we will take them into
consideration for their first occurrence. So result will be 1 * 2 * 3 * 4 * 5 = 120
Input-: arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4 }
Output-: 32400
Explanation-: Since 10 and 4 are repeating more than once so we will take them into consideration
for their first occurrence. So result will be 1 * 10 * 9 * 4 * 2 * 45  = 32400

Approach used in the below program is as follows

• Input the duplicate elements in an array
• For the better approach sort the elements of an array in ascending order such that it would be easy to determine which array element is repeating and don’t consider it for the product
• Find all the distinct elements in an array and keep multiplying them by storing the result
• Display the final result as the product of all the distinct elements in an array

## Algorithm

Start
Step 1-> Declare function to find the product of all the distinct elements in an array
int find_Product(int arr[], int size)
Declare and set int prod = 1
Create variable as unordered_set<int> s
Loop For  i = 0 and i < size and i++
IF s.find(arr[i]) = s.end()
Set  prod *= arr[i]
Call s.insert(arr[i])
End
End
return prod
Step 2 -: In main()
Declare and set int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 }
Calculate the size of an array int size = sizeof(arr) / sizeof(int)
Call find_Product(arr, size)
Stop

## Example

include <bits/stdc++.h>
using namespace std;
//function that calculate the product of non-repeating elements
int find_Product(int arr[], int size) {
int prod = 1;
unordered_set<int> s;
for (int i = 0; i < size; i++) {
if (s.find(arr[i]) == s.end()) {
prod *= arr[i];
s.insert(arr[i]);
}
}
return prod;
}
int main() {
int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 };
int size = sizeof(arr) / sizeof(int);
cout<<"product of all non-repeated elements are : "<<find_Product(arr, size);
return 0;
}

## Output

product of all non-repeated elements are : 120