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

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.

Java Code:

Output:

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

__________________________________________________ Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________