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 elementsInput : 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++ code for the approach #include <bits/stdc++.h> using namespace std;
// Function to find the product of all // non-repeated elements in an array int productOfDistinct( int arr[], int n) {
int product = 1;
// Loop through every element of the array
for ( int i = 0; i < n; i++) {
bool isDistinct = true ;
// Check if the element is present on the left side of it
for ( int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
isDistinct = false ;
break ;
}
}
// If the element is distinct, multiply it to the product
if (isDistinct) {
product *= arr[i];
}
}
// Return the product of distinct elements
return product;
} // Driver's code int main() {
// Input
int arr[] = { 1, 2, 3, 1, 1, 4, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
// Find the product of distinct elements in the array
int product = productOfDistinct(arr, n);
// Print the product
cout << product << endl;
return 0;
} |
// Java code for the approach import java.util.HashSet;
public class Main {
// Function to find the product of all non-repeated elements in an array
static int productOfDistinct( int [] arr, int n) {
int product = 1 ;
// Creating a set to track distinct elements
HashSet<Integer> distinctElements = new HashSet<>();
// iterate over every element of the array
for ( int i = 0 ; i < n; i++) {
// Check if the element is distinct
if (!distinctElements.contains(arr[i])) {
product *= arr[i];
distinctElements.add(arr[i]);
}
}
// Return the product of distinct elements
return product;
}
// Driver code
public static void main(String[] args) {
// Input
int [] arr = { 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 };
int n = arr.length;
// Find the product of distinct elements in the array
int product = productOfDistinct(arr, n);
// Print the product
System.out.println(product);
}
} |
# Function to find the product of all # non-repeated elements in an array def productOfDistinct(arr):
product = 1
# Loop through every element of the array
for i in range ( len (arr)):
isDistinct = True
# Check if the element is present on the left side of it
for j in range (i):
if arr[i] = = arr[j]:
isDistinct = False
break
# If the element is distinct, multiply it to the product
if isDistinct:
product * = arr[i]
# Return the product of distinct elements
return product
# Driver's code if __name__ = = '__main__' :
# Input
arr = [ 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 ]
# Find the product of distinct elements in the array
product = productOfDistinct(arr)
# Print the product
print (product)
|
using System;
class Program
{ // Function to find the product of all
// non-repeated elements in an array
static int ProductOfDistinct( int [] arr)
{
int product = 1;
// Loop through every element of the array
for ( int i = 0; i < arr.Length; i++)
{
bool isDistinct = true ;
// Check if the element is present on the left side of it
for ( int j = 0; j < i; j++)
{
if (arr[i] == arr[j])
{
isDistinct = false ;
break ;
}
}
// If the element is distinct, multiply it to the product
if (isDistinct)
{
product *= arr[i];
}
}
// Return the product of distinct elements
return product;
}
// Driver's code
static void Main( string [] args)
{
// Input
int [] arr = { 1, 2, 3, 1, 1, 4, 5, 6 };
// Find the product of distinct elements in the array
int product = ProductOfDistinct(arr);
// Print the product
Console.WriteLine(product);
}
} |
// Function to find the product of all non-repeated elements in an array function productOfDistinct(arr) {
let product = 1;
// Loop through every element of the array
for (let i = 0; i < arr.length; i++) {
let isDistinct = true ;
// Check if the element is present on the left side of it
for (let j = 0; j < i; j++) {
if (arr[i] === arr[j]) {
isDistinct = false ;
break ;
}
}
// If the element is distinct, multiply it to the product
if (isDistinct) {
product *= arr[i];
}
}
// Return the product of distinct elements
return product;
} // Driver's code const arr = [1, 2, 3, 1, 1, 4, 5, 6]; // Find the product of distinct elements in the array const product = productOfDistinct(arr); // Print the product console.log(product); |
720
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++ 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 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 |
# 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# 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 |
<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> |
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:
// 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 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 */ |
# 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# 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 |
<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> |
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.
- In JavaScript, the frequency is getting calculated by the single for loop
Below is the implementation of this approach:
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;
// c++ program for the above approach int sumOfElements(vector< int >& arr, int n)
{ // loop to calculate frequency of elements of array
map< int , int > freq;
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
}
// Converting keys of freq dictionary to list
vector< int > lis;
for ( auto x : arr) {
lis.push_back(x);
}
// Return product of list
int product = 1;
for ( int i = 0; i < lis.size(); i++) {
product *= lis[i];
}
return product;
} // Driver code int main()
{ // Driver code
vector< int > arr = { 1, 2, 3, 1, 1, 4, 5, 6 };
int n = arr.size();
cout << (sumOfElements(arr, n));
return 0;
} // The code is contributed by Nidhi goel. |
// Java program for the above approach import java.util.*;
public class Main {
public static int sumOfElements(ArrayList<Integer> arr, int n) {
// loop to calculate frequency of elements of array
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 );
}
// Converting keys of freq dictionary to list
ArrayList<Integer> lis = new ArrayList<Integer>(arr);
// Return product of list
int product = 1 ;
for ( int i = 0 ; i < lis.size(); i++) {
product *= lis.get(i);
}
return product;
}
public static void main(String[] args) {
// Driver code
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));
}
} // This code is contributed by sdeadityasharma |
# 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 |
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) {
// Counter function is used to calculate frequency of elements of array
Dictionary< int , int > freq = arr.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
// Converting keys of freq dictionary to list
List< int > lis = freq.Keys.ToList();
// Return product of list
int product = 1;
foreach ( int i in lis) {
product *= i;
}
return product;
}
} |
// JavaScript program for the above approach function sumOfElements(arr, n){
// loop to calculate frequency of elements of array
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);
}
}
// Converting keys of freq dictionary to list
let lis = Array.from(freq.keys());
// Return product of list
let product = 1;
for (let i = 0; i < lis.length; i++) {
product *= lis[i];
}
return product;
} // Driver code let arr = [1, 2, 3, 1, 1, 4, 5, 6]; let n = arr.length; console.log(sumOfElements(arr, n)); |
720
Complexity analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(N)