This article explores different ways to find duplicates in an array in Kotlin.

1. Using a Set

A simple solution is to loop through the array and keep track of all visited elements in a Set. If an element is encountered before, mark it as duplicate. Finally, report all duplicates after processing each element.

Download Code

 
The code can be easily shortened using the filter() function:

Download Code

2. Using filter() function

Another solution is to filter duplicate elements in the array using the filter() function with the count() function. This logic would translate to the following code:

Download Code

3. Using a Frequency Map

The above implementation calls the count() function for each array element, which will lead to poor performance for large arrays. A better solution is to create a frequency map and filter all values with a frequency greater than 1.

Download Code

 
Alternatively, we can use the groupBy() library function to group values by the key, such that we get a map where each group key is associated with a list of the corresponding mapping. Then the problem reduces to filtering the values with the size more than 1 and returning their keys. Here’s what the code would look like:

Download Code

That’s all about finding duplicates in an array in Kotlin.