Check if all array elements are distinct
Last Updated :
29 Dec, 2022
Given an array, check whether all elements in an array are distinct or not.
Examples:
Input : 1, 3, 2, 4
Output : Yes
Input : “Geeks”, “for”, “Geeks”
Output : No
Input : “All”, “Not”, “Equal”
Output : Yes
One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return True. If no element repeats, return false.
An efficient solution is to Hashing. We put all array elements in a HashSet. If size of HashSet remains same as array size, then we return true.
C++
#include <bits/stdc++.h>
using namespace std;
bool areDistinct(vector< int > arr)
{
int n = arr.size();
unordered_set< int > s;
for ( int i = 0; i < n; i++) {
s.insert(arr[i]);
}
return (s.size() == arr.size());
}
int main()
{
std::vector< int > arr = { 1, 2, 3, 2 };
if (areDistinct(arr)) {
cout << "All Elements are Distinct" ;
}
else {
cout << "Not all Elements are Distinct" ;
}
return 0;
}
|
Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class DistinctElements {
public static boolean areDistinct(Integer arr[])
{
Set<Integer> s =
new HashSet<Integer>(Arrays.asList(arr));
return (s.size() == arr.length);
}
public static void main(String[] args)
{
Integer[] arr = { 1 , 2 , 3 , 2 };
if (areDistinct(arr))
System.out.println( "All Elements are Distinct" );
else
System.out.println( "Not all Elements are Distinct" );
}
}
|
Python3
def areDistinct(arr) :
n = len (arr)
s = set ()
for i in range ( 0 , n):
s.add(arr[i])
return ( len (s) = = len (arr))
arr = [ 1 , 2 , 3 , 2 ]
if (areDistinct(arr)):
print ( "All Elements are Distinct" )
else :
print ( "Not all Elements are Distinct" )
|
C#
using System;
using System.Collections.Generic;
public class DistinctElements
{
public static bool areDistinct( int []arr)
{
HashSet< int > s = new HashSet< int >(arr);
return (s.Count == arr.Length);
}
public static void Main(String[] args)
{
int [] arr = { 1, 2, 3, 2 };
if (areDistinct(arr))
Console.WriteLine( "All Elements are Distinct" );
else
Console.WriteLine( "Not all Elements are Distinct" );
}
}
|
Javascript
<script>
function areDistinct(arr)
{
let n = arr.length;
let s = new Set();
for (let i = 0; i < n; i++) {
s.add(arr[i]);
}
return (s.size == arr.length);
}
let arr = [ 1, 2, 3, 2 ];
if (areDistinct(arr)) {
document.write( "All Elements are Distinct" );
}
else {
document.write( "Not all Elements are Distinct" );
}
</script>
|
Output
Not all Elements are Distinct
Time complexity: O(n) where n is the size of the given array
Auxiliary space: O(n)
Share your thoughts in the comments
Please Login to comment...