Keep only the largest k values by maintaining a small min-heap.

Algorithm

Steps

  1. Store the heap in an array.
  2. Compare parent and child indexes instead of building explicit tree nodes.
  3. Swap only when the heap order is violated.
  4. Print the deterministic final heap state for replay comparison.

Complexity

  • Time: O(n log k)
  • Space: O(k)
bounded heap For top-k largest values, a min-heap of size k keeps the current cutoff at the root.

Kotlin DSA Implementation

basic.kt
fun listString(values: List<Int>) = values.joinToString(", ", "[", "]")
fun heapInsert(heap: MutableList<Int>, value: Int) {
    heap.add(value)
    var child = heap.lastIndex
    while (child > 0) {
        val parent = (child - 1) / 2
        if (heap[parent] <= heap[child]) break
        val tmp = heap[parent]; heap[parent] = heap[child]; heap[child] = tmp
        child = parent
    }
}
fun heapPop(heap: MutableList<Int>): Int {
    val smallest = heap[0]
    heap[0] = heap.removeAt(heap.lastIndex)
    var parent = 0
    while (true) {
        val left = parent * 2 + 1
        val right = left + 1
        if (left >= heap.size) break
        var child = left
        if (right < heap.size && heap[right] < heap[left]) child = right
        if (heap[parent] <= heap[child]) break
        val tmp = heap[parent]; heap[parent] = heap[child]; heap[child] = tmp
        parent = child
    }
    return smallest
}
fun main() { val heap = mutableListOf<Int>(); for (value in listOf(5, 1, 9, 3, 7, 2)) { heapInsert(heap, value); if (heap.size > 3) heapPop(heap) }; val top = heap.sortedDescending(); println(listString(top)) }

Output

[9, 7, 5]

Implementation notes

  • Kotlin keeps the working heap in val heap = mutableListOf<Int>(), a MutableList<Int> whose binding is stable while helper calls mutate its contents.
  • The input stream is listOf(5, 1, 9, 3, 7, 2). Each loop value is inserted with heapInsert(heap, value).
  • heapInsert appends with heap.add(value), then sifts up using heap.lastIndex, parent index (child - 1) / 2, min-heap comparison heap[parent] <= heap[child], and explicit temp-variable swaps.
  • Size is bounded by if (heap.size > 3) heapPop(heap), so values are inserted first and then the current minimum is evicted when the heap grows past k.
  • heapPop removes the cutoff value by copying heap[0], replacing the root with heap.removeAt(heap.lastIndex), and sifting down with child indexes parent * 2 + 1 and left + 1.
  • Evicted values are not collected; the retained heap holds the top three values as a min-heap.
  • The trace shows heap states [5], [1, 5], [1, 5, 9], [3, 5, 9], [5, 7, 9], and [5, 7, 9] after considering 2.
  • val top = heap.sortedDescending() creates the output list in high-to-low order, and println(listString(top)) prints [9, 7, 5].