Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 06 Sep, 2022
View Discussion
Improve Article
Save Article

Given an integer array with duplicate elements. The task is to find the product of all distinct elements in the given array.

Examples

Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10}; 
Output : 97200 
Here we take 12, 10, 9, 45, 2 for product 
because these are the only distinct elements 

Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4}; 
Output : 32400 

A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on the left side of it. If present, then ignores the element.

Complexity Analysis:

  • Time Complexity: O(N2
  • Auxiliary Space: O(1)

A Better Solution to this problem is to first sort all elements of the array in ascending order and find one by one distinct element in the array. Finally, find the product of all distinct elements.

Below is the implementation of this approach: 

C++




// C++ program to find the product of all
// non-repeated elements in an array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the product of all
// non-repeated elements in an array
int findProduct(int arr[], int n)
{
    // sort all elements of array
    sort(arr, arr + n);
 
    int prod = 1;
    for (int i = 0; i < n; i++) {
        if (arr[i] != arr[i + 1])
            prod = prod * arr[i];
    }
 
    return prod;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 1, 1, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(int);
 
    cout << findProduct(arr, n);
 
    return 0;
}

Java




// Java program to find the product of all
// non-repeated elements in an array
import java.util.Arrays;
 
class GFG {
 
// Function to find the product of all
// non-repeated elements in an array
static int findProduct(int arr[], int n)
{
    // sort all elements of array
    Arrays.sort(arr);
     
    int prod = 1 * arr[0];
    for (int i = 0; i < n - 1; i++)
    {
        if (arr[i] != arr[i + 1])
        {
            prod = prod * arr[i + 1];
        }
         
    }
    return prod;
}
 
// Driver code
public static void main(String[] args) {
    int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
    int n = arr.length;
    System.out.println(findProduct(arr, n));
    }
}
 
// This code is contributed by PrinciRaj1992

Python3




# Python 3 program to find the product
# of all non-repeated elements in an array
 
# Function to find the product of all
# non-repeated elements in an array
def findProduct(arr, n):
     
    # sort all elements of array
    sorted(arr)
 
    prod = 1
    for i in range(0, n, 1):
        if (arr[i - 1] != arr[i]):
            prod = prod * arr[i]
 
    return prod;
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 1, 1, 4, 5, 6]
 
    n = len(arr)
 
    print(findProduct(arr, n))
 
# This code is contributed by
# Surendra_Gangwar

C#




// C# program to find the product of all
// non-repeated elements in an array
using System;
 
class GFG
{
 
// Function to find the product of all
// non-repeated elements in an array
static int findProduct(int []arr, int n)
{
    // sort all elements of array
    Array.Sort(arr);
     
    int prod = 1 * arr[0];
    for (int i = 0; i < n - 1; i++)
    {
        if (arr[i] != arr[i + 1])
        {
            prod = prod * arr[i + 1];
        }
         
    }
    return prod;
}
 
// Driver code
public static void Main()
{
    int []arr = {1, 2, 3, 1, 1, 4, 5, 6};
    int n = arr.Length;
    Console.WriteLine(findProduct(arr, n));
}
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
// javascript program to find the product of all
// non-repeated elements in an array
 
    // Function to find the product of all
    // non-repeated elements in an array
    function findProduct(arr , n) {
        // sort all elements of array
        arr.sort();
 
        var prod = 1 * arr[0];
        for (i = 0; i < n - 1; i++) {
            if (arr[i] != arr[i + 1]) {
                prod = prod * arr[i + 1];
            }
 
        }
        return prod;
    }
 
    // Driver code
     
        var arr = [ 1, 2, 3, 1, 1, 4, 5, 6 ];
        var n = arr.length;
        document.write(findProduct(arr, n));
 
// This code contributed by gauravrajput1
</script>

Output

720

Complexity Analysis:

  • Time Complexity: O(N * log N) 
  • Auxiliary Space: O(1)

An Efficient Solution is to traverse the array and keep a hash map to check if the element is repeated or not. While traversing if the current element is already present in the hash or not, if yes then it means it is repeated and should not be multiplied with the product, if it is not present in the hash then multiply it with the product and insert it into hash.

Below is the implementation of this approach: 

CPP




// C++ program to find the product of all
// non- repeated elements in an array
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the product of all
// non-repeated elements in an array
int findProduct(int arr[], int n)
{
    int prod = 1;
 
    // Hash to store all element of array
    unordered_set<int> s;
    for (int i = 0; i < n; i++) {
        if (s.find(arr[i]) == s.end()) {
            prod *= arr[i];
            s.insert(arr[i]);
        }
    }
 
    return prod;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 1, 1, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(int);
 
    cout << findProduct(arr, n);
 
    return 0;
}

Java




// Java program to find the product of all
// non- repeated elements in an array
import java.util.HashSet;
 
class GFG
{
 
    // Function to find the product of all
    // non-repeated elements in an array
    static int findProduct(int arr[], int n)
    {
        int prod = 1;
 
        // Hash to store all element of array
        HashSet<Integer> s = new HashSet<>();
        for (int i = 0; i < n; i++)
        {
            if (!s.contains(arr[i]))
            {
                prod *= arr[i];
                s.add(arr[i]);
            }
        }
 
        return prod;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
        int n = arr.length;
 
        System.out.println(findProduct(arr, n));
    }
}
 
/* This code contributed by PrinciRaj1992 */

Python




# Python3 program to find the product of all
# non- repeated elements in an array
 
# Function to find the product of all
# non-repeated elements in an array
def findProduct( arr, n):
 
    prod = 1
 
    # Hash to store all element of array
    s = dict()
    for i in range(n):
        if (arr[i] not in s.keys()):
            prod *= arr[i]
            s[arr[i]] = 1
     
    return prod
 
# Driver code
arr= [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
 
print(findProduct(arr, n))
 
# This code is contributed by mohit kumar

C#




// C# program to find the product of all
// non- repeated elements in an array
using System;
using System.Collections.Generic;
     
class GFG
{
 
    // Function to find the product of all
    // non-repeated elements in an array
    static int findProduct(int []arr, int n)
    {
        int prod = 1;
 
        // Hash to store all element of array
        HashSet<int> s = new HashSet<int>();
        for (int i = 0; i < n; i++)
        {
            if (!s.Contains(arr[i]))
            {
                prod *= arr[i];
                s.Add(arr[i]);
            }
        }
 
        return prod;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = {1, 2, 3, 1, 1, 4, 5, 6};
        int n = arr.Length;
 
        Console.WriteLine(findProduct(arr, n));
    }
}
 
// This code is contributed by Princi Singh

Javascript




<script>
 
// JavaScript program to find the product of all
// non- repeated elements in an array
 
// Function to find the product of all
// non-repeated elements in an array
function findProduct(arr,n)
{
    let prod = 1;
  
        // Hash to store all element of array
        let s = new Set();
        for (let i = 0; i < n; i++)
        {
            if (!s.has(arr[i]))
            {
                prod *= arr[i];
                s.add(arr[i]);
            }
        }
  
        return prod;
}
 
// Driver code
let arr=[1, 2, 3, 1, 1, 4, 5, 6];
let n = arr.length;
document.write(findProduct(arr, n));
 
 
// This code is contributed by patel2127
 
</script>

Output

720

Complexity Analysis:

  • Time Complexity: O(N) 
  • Auxiliary Space: O(N)

Another Approach (Using Built-in Python functions): 

Steps to find the product of unique elements:

  • Calculate the frequencies using the Counter() function
  • Convert the frequency keys to the list.
  • Calculate the product of the list.

Below is the implementation of this approach: 

Python3




# Python program for the above approach
from collections import Counter
 
# Function to return the product of distinct elements
def sumOfElements(arr, n):
 
    # Counter function is used to
    # calculate frequency of elements of array
    freq = Counter(arr)
     
    # Converting keys of freq dictionary to list
    lis = list(freq.keys())
     
    # Return product of list
    product=1
    for i in lis:
        product*=i
    return product
 
 
# Driver code
if __name__ == "__main__":
 
    arr = [1, 2, 3, 1, 1, 4, 5, 6]
    n = len(arr)
 
    print(sumOfElements(arr, n))
 
# This code is contributed by Pushpesh Raj

Output

720

Complexity analysis:

  • Time Complexity: O(N) 
  • Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!