How to group elements of an array based on their first occurrence in Kotlin

1 Answer

0 votes
const val MAX_VALUE = 100 // Assumes values are between 0 and 99

fun groupElements(arr: IntArray): IntArray {
    val frequency = IntArray(MAX_VALUE) { 0 }
    val order = mutableListOf<Int>()
    val result = mutableListOf<Int>()

    // Count frequencies and track order of first occurrences
    for (num in arr) {
        if (frequency[num] == 0) {
            order.add(num)
        }
        frequency[num]++
    }

    // Group elements based on their first occurrence
    for (num in order) {
        repeat(frequency[num]) {
            result.add(num)
        }
    }

    return result.toIntArray()
}

fun main() {
    val arr = intArrayOf(88, 33, 77, 88, 22, 55, 88, 55, 11, 99, 88, 11, 77)
    val grouped = groupElements(arr)

    print("Grouped vector: ")
    println(grouped.joinToString(" "))
}



/*
run:

Grouped vector: 88 88 88 88 33 77 77 22 55 55 11 11 99

*/

 



answered Oct 11, 2025 by avibootz
...