Check for duplicates in an array in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <T> hasDuplicates(arr: Array<T>): Boolean { return arr.size != arr.distinct().count(); } fun main() { val arr: Array<Int> = arrayOf(4, 6, 8, 3, 4) if (hasDuplicates(arr)) { println("Repeated elements found") } else { println("No repeated elements found") } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <T> hasDuplicates(arr: Array<T>): Boolean { return arr.size != hashSetOf(*arr).size } fun main() { val arr: Array<Int> = arrayOf(4, 6, 8, 3, 4) if (hasDuplicates(arr)) { println("Repeated elements found") } else { println("No repeated elements found") } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
fun <T> hasDuplicates(arr: Array<T>): Boolean { arr.sort() // sort the array var previous: T? = null for (e in arr) { if (e != null && e == previous) { return true } previous = e } return false // no repeated elements } fun main() { val arr: Array<Int> = arrayOf(4, 6, 8, 3, 4) if (hasDuplicates(arr)) { println("Repeated elements found") } else { println("No repeated elements found") } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
fun <T> hasDuplicates(arr: Array<T>): Boolean { for (i in arr.indices) { for (j in i + 1 until arr.size) { if (arr[i] == arr[j]) { return true } } } return false // no repeated elements } fun main() { val arr: Array<Int> = arrayOf(4, 6, 8, 3, 4) if (hasDuplicates(arr)) { println("Repeated elements found") } else { println("No repeated elements found") } } |
That’s all about checking for duplicates in an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)