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
- Count distinct elements in an array
- Distinct adjacent elements in an array
- Print sorted distinct elements of array
- Product of non-repeating (distinct) elements in an Array
- Print All Distinct Elements of a given integer array
- Find sum of non-repeating (distinct) elements in an array
- Third largest element in an array of distinct elements
- Distinct adjacent elements in a binary array
- Find minimum changes required in an array for it to contain k distinct elements
- Count subarrays having total distinct elements same as original array
- Making elements distinct in a sorted array by minimum increments
- 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
- Queries for number of distinct elements from a given index till last index in an array
- Check if all elements of the array are palindrome or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.