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.
Algorithm:
- Define a function named productOfDistinct that takes an integer array arr and its size n as input.
- Initialize product variable to 1.
- Loop through every element of the array using a for loop.
- Set a boolean flag isDistinct to true.
- Loop through all the previous elements of the array using another for loop.
- If the current element arr[i] is equal to any previous element arr[j], set isDistinct to false and break the loop.
- If the element is distinct, multiply it to the product.
- Return the product of distinct elements.
- In the main function, define an integer array arr and its size n.
- Call the productOfDistinct function with arr and n as arguments.
- Print the product of distinct elements.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
int productOfDistinct( int arr[], int n) {
int product = 1;
for ( int i = 0; i < n; i++) {
bool isDistinct = true ;
for ( int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
isDistinct = false ;
break ;
}
}
if (isDistinct) {
product *= arr[i];
}
}
return product;
}
int main() {
int arr[] = { 1, 2, 3, 1, 1, 4, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
int product = productOfDistinct(arr, n);
cout << product << endl;
return 0;
}
|
Java
import java.util.HashSet;
public class Main {
static int productOfDistinct( int [] arr, int n) {
int product = 1 ;
HashSet<Integer> distinctElements = new HashSet<>();
for ( int i = 0 ; i < n; i++) {
if (!distinctElements.contains(arr[i])) {
product *= arr[i];
distinctElements.add(arr[i]);
}
}
return product;
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 };
int n = arr.length;
int product = productOfDistinct(arr, n);
System.out.println(product);
}
}
|
Python3
def productOfDistinct(arr):
product = 1
for i in range ( len (arr)):
isDistinct = True
for j in range (i):
if arr[i] = = arr[j]:
isDistinct = False
break
if isDistinct:
product * = arr[i]
return product
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 ]
product = productOfDistinct(arr)
print (product)
|
C#
using System;
class Program
{
static int ProductOfDistinct( int [] arr)
{
int product = 1;
for ( int i = 0; i < arr.Length; i++)
{
bool isDistinct = true ;
for ( int j = 0; j < i; j++)
{
if (arr[i] == arr[j])
{
isDistinct = false ;
break ;
}
}
if (isDistinct)
{
product *= arr[i];
}
}
return product;
}
static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 1, 1, 4, 5, 6 };
int product = ProductOfDistinct(arr);
Console.WriteLine(product);
}
}
|
Javascript
function productOfDistinct(arr) {
let product = 1;
for (let i = 0; i < arr.length; i++) {
let isDistinct = true ;
for (let j = 0; j < i; j++) {
if (arr[i] === arr[j]) {
isDistinct = false ;
break ;
}
}
if (isDistinct) {
product *= arr[i];
}
}
return product;
}
const arr = [1, 2, 3, 1, 1, 4, 5, 6];
const product = productOfDistinct(arr);
console.log(product);
|
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++
#include <bits/stdc++.h>
using namespace std;
int findProduct( int arr[], int n)
{
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;
}
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
import java.util.Arrays;
class GFG {
static int findProduct( int arr[], int n)
{
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;
}
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));
}
}
|
Python3
def findProduct(arr, n):
sorted (arr)
prod = 1
for i in range ( 0 , n, 1 ):
if (arr[i - 1 ] ! = arr[i]):
prod = prod * arr[i]
return prod;
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 ]
n = len (arr)
print (findProduct(arr, n))
|
C#
using System;
class GFG
{
static int findProduct( int []arr, int n)
{
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;
}
public static void Main()
{
int []arr = {1, 2, 3, 1, 1, 4, 5, 6};
int n = arr.Length;
Console.WriteLine(findProduct(arr, n));
}
}
|
Javascript
<script>
function findProduct(arr , n) {
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;
}
var arr = [ 1, 2, 3, 1, 1, 4, 5, 6 ];
var n = arr.length;
document.write(findProduct(arr, n));
</script>
|
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
#include <bits/stdc++.h>
using namespace std;
int findProduct( int arr[], int n)
{
int prod = 1;
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;
}
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
import java.util.HashSet;
class GFG
{
static int findProduct( int arr[], int n)
{
int prod = 1 ;
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;
}
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));
}
}
|
Python
def findProduct( arr, n):
prod = 1
s = dict ()
for i in range (n):
if (arr[i] not in s.keys()):
prod * = arr[i]
s[arr[i]] = 1
return prod
arr = [ 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 ]
n = len (arr)
print (findProduct(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int findProduct( int []arr, int n)
{
int prod = 1;
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;
}
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));
}
}
|
Javascript
<script>
function findProduct(arr,n)
{
let prod = 1;
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;
}
let arr=[1, 2, 3, 1, 1, 4, 5, 6];
let n = arr.length;
document.write(findProduct(arr, n));
</script>
|
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.
- In JavaScript, the frequency is getting calculated by the single for loop
Below is the implementation of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sumOfElements(vector< int >& arr, int n)
{
map< int , int > freq;
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
}
vector< int > lis;
for ( auto x : arr) {
lis.push_back(x);
}
int product = 1;
for ( int i = 0; i < lis.size(); i++) {
product *= lis[i];
}
return product;
}
int main()
{
vector< int > arr = { 1, 2, 3, 1, 1, 4, 5, 6 };
int n = arr.size();
cout << (sumOfElements(arr, n));
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int sumOfElements(ArrayList<Integer> arr, int n) {
Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
for ( int i = 0 ; i < n; i++) {
freq.put(arr.get(i), freq.getOrDefault(arr.get(i), 0 ) + 1 );
}
ArrayList<Integer> lis = new ArrayList<Integer>(arr);
int product = 1 ;
for ( int i = 0 ; i < lis.size(); i++) {
product *= lis.get(i);
}
return product;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList( 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 ));
int n = arr.size();
System.out.println(sumOfElements(arr, n));
}
}
|
Python3
from collections import Counter
def sumOfElements(arr, n):
freq = Counter(arr)
lis = list (freq.keys())
product = 1
for i in lis:
product * = i
return product
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 ]
n = len (arr)
print (sumOfElements(arr, n))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main( string [] args) {
int [] arr = {1, 2, 3, 1, 1, 4, 5, 6};
int n = arr.Length;
Console.WriteLine(sumOfElements(arr, n));
}
static int sumOfElements( int [] arr, int n) {
Dictionary< int , int > freq = arr.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
List< int > lis = freq.Keys.ToList();
int product = 1;
foreach ( int i in lis) {
product *= i;
}
return product;
}
}
|
Javascript
function sumOfElements(arr, n){
let freq = new Map();
for (let i = 0; i < n; i++) {
if (freq.has(arr[i])) {
freq.set(arr[i], freq.get(arr[i])+1);
} else {
freq.set(arr[i], 1);
}
}
let lis = Array.from(freq.keys());
let product = 1;
for (let i = 0; i < lis.length; i++) {
product *= lis[i];
}
return product;
}
let arr = [1, 2, 3, 1, 1, 4, 5, 6];
let n = arr.length;
console.log(sumOfElements(arr, n));
|
Complexity analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!