Design a class KthLargest(k, initial[]) that tracks the k-th largest element in a stream. Each call to add(val) inserts the value and returns the current k-th largest.
Constraints: `1 ≤ k ≤ 10^4` · `-10^4 ≤ val ≤ 10^4` · at least `k + 1` total elements by query time · answer must be returned after every `add`.
Here is a stream of numbers arriving one at a time. After each arrival, you owe the caller the 5-th largest so far — before the next number shows up. The obvious shot: keep them in a sorted array and read index n - 5.
Tap each incoming value to drop it into the right slot. The counter under the shelf counts every element the array has to shift right to make room. Watch it climb.
The ring marks index n − k — the only slot you ever read.
// Sorted-array baseline — O(n) per add (binary search + shift).add(val) { let lo = 0, hi = this.arr.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (this.arr[mid] < val) lo = mid + 1; else hi = mid; } this.arr.splice(lo, 0, val); // O(n) shift — the hot spot return this.arr[this.arr.length - this.k];}