Product of non-repeating (distinct) elements in an Array
Last Updated :
11 Jul, 2025
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++
// 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
// 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);
}
}
Python3
# 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)
C#
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);
}
}
JavaScript
// 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);
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>
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>
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++
// 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
// 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
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
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) {
// 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
// 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));
Complexity analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem