This article explores different ways to check for repeated elements in an array in Kotlin.

1. Using distinct() function

Kotlin has a distinct() function, which returns a list of distinct elements present in the array. If the count of the returned list is not equal to the original array’s length, you can say that the array contains a repeated element.

Download Code

2. Using HashSet

Alternatively, you can insert all the array elements into a HashSet, which doesn’t allow repeated values. Now, if the array’s length is not equal to the set’s size, you can say that the array contains the repeated element.

Download Code

3. Using Sorting

Here, the idea is to sort the array and compare its adjacent elements. If any of the adjacent elements are equal, you can say that the array contains a repeated element.

Download Code

 
Note this solution changes the original order of the array and takes more time than the alternatives discussed above.

4. Custom Routine

A naive solution is to use nested for-loops to determine whether an element in the array is repeated. However, this solution is not preferable for large arrays.

Download Code

That’s all about checking for duplicates in an array in Kotlin.