Given an array, check whether all elements in an array are distinct or not.
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 false. 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.
# Python3 program to check if all array
# elements are distinct
def areDistinct(arr) :
n = len(arr)
# Put all array elements in a map
s = set()
for i in range(0, n):
# If all elements are distinct,
# size of set should be same array.
return (len(s) == len(arr))
# Driver code
arr = [ 1, 2, 3, 2 ]
print(“All Elements are Distinct”)
print(“Not all Elements are Distinct”)
# This code is contributed by ihritik
Not all Elements are Distinct
- Distinct adjacent elements in an array
- Count distinct elements in an array
- Print All Distinct Elements of a given integer array
- Product of non-repeating (distinct) elements in an Array
- Find sum of non-repeating (distinct) elements in an array
- Third largest element in an array of distinct elements
- Print sorted distinct elements of array
- Making elements distinct in a sorted array by minimum increments
- Count subarrays having total distinct elements same as original array
- Construct a distinct elements array with given size, sum and element upper bound
- Check if there exist two elements in an array whose sum is equal to the sum of rest of the array
- Check if all elements of the array are palindrome or not
- Check if an array contains all elements of a given range
- Check if a given array contains duplicate elements within k distance from each other
- Maximum distinct elements after removing k elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.