Skip to content

Files

Latest commit

734aa35 · Jun 5, 2025

History

History
23 lines (18 loc) · 583 Bytes

703.kth-largest-element-in-a-stream.md

File metadata and controls

23 lines (18 loc) · 583 Bytes

Heap

To find the kth largest element in a stream, we can use a min heap of fixed size k to maintain the k largest elements.

class KthLargest(private val k: Int, private val nums: IntArray) {

    private val minHeap = PriorityQueue<Int>()

    init {
        for (num in nums) {
            add(num)
        }
    }

    fun add(`val`: Int): Int {
        minHeap.add(`val`)
        if (minHeap.size > k) minHeap.poll()
        return minHeap.peek()
    }
}