Beginner

# 355. Product of all Unique elements in a given array

Objective: Given an array of integers which contains duplicates as well. Write a program to find the product of all unique elements in the array. This problem is also referred as find the product  of all distinct elements in the array

Example:

```[] arrA = {1, 6, 4, 3, 2, 2, 3, 8, 1};
Output : 24
(Unique elements are: 1, 6, 4, 3, 2, 8)
```

Approach:

Use Sorting-

• Sort the array, this will bring all duplicates together.
• Iterate through array and get the product of all unique elements (If current element which is same as the previous element, ignore the current element).

Time Complexity: O(NlogN)

Use Hash Set-

• Create Hash Set and initialize product = 1.
• Iterate through array, check if current element is in Hash Set, if yes then ignore the element else multiply the element to the product and add it to the Hash Set.

Time Complexity: O(N), Space Complexity: O(N)

See the code below for both the approaches for better understanding.

Output:

```Product of all Unique elements (Sorting Method): 1152
Product of all Unique elements (HashSet Method: 1152
```