How to find duplicate elements in an array with Kotln

2 Answers

0 votes
fun findDuplicates(array: IntArray): Set<Int> {
    val seen = mutableSetOf<Int>()
    
    return array.filter { !seen.add(it) }.toSet()
}

fun main() {
    val values = intArrayOf(1, 2, 3, 2, 2, 4, 4, 4, 4, 3, 5, 6, 3)

    val duplicates = findDuplicates(values)
    
    println(duplicates) 
}



/*
run:
  
[2, 4, 3]
  
*/

 



answered Oct 26, 2024 by avibootz
edited Oct 26, 2024 by avibootz
0 votes
fun findDuplicates(array: IntArray): Set<Int> {
    val seen = mutableSetOf<Int>()
    val duplicates = mutableSetOf<Int>()
    
    for (element in array) {
        if (!seen.add(element)) {
            duplicates.add(element)
        }
    }
    
    return duplicates
}

fun main() {
    val values = intArrayOf(1, 2, 3, 2, 2, 4, 4, 4, 4, 3, 5, 6, 3)
    
    val duplicates = findDuplicates(values)
    
    println(duplicates) 
}



/*
run:
  
[2, 4, 3]
  
*/

 



answered Oct 26, 2024 by avibootz
...