# Keep the k largest values of a stream

> Hold a min heap of size k and replace its root whenever a larger value arrives.

**Few items**

```ts
import { minBinaryHeap, numberOrder } from 'knotkit/heap'

const k = 3
const largest = minBinaryHeap(numberOrder)

for (const latency of [120, 45, 300, 87, 210, 95, 410]) {
  if (largest.size < k) {
    largest.push(latency)
  } else if (latency > largest.peek()) {
    largest.replaceRoot(latency)
  }
}

const top: number[] = []

while (largest.size > 0) {
  top.push(largest.pop())
}

top // [210, 300, 410]
```

**Thousands of items**

```ts
import { minBinaryHeap, numberOrder } from 'knotkit/heap'
import { splitmix32, uniformInt } from 'knotkit/prng'

const k = 3
const random = splitmix32(2026)

// 20,000 request latencies in arrival order, plus one outlier inserted at a seeded position.
const latencies = Array.from({ length: 20_000 }, () => uniformInt(random, 1_000) + 1)
latencies.splice(uniformInt(random, latencies.length), 0, 1_500)

latencies.indexOf(1_500) // 1710

const largest = minBinaryHeap(numberOrder)

for (const latency of latencies) {
  if (largest.size < k) {
    largest.push(latency)
  } else if (latency > largest.peek()) {
    largest.replaceRoot(latency)
  }
}

const top: number[] = []

while (largest.size > 0) {
  top.push(largest.pop())
}

// The heap held three values through 20,001 arrivals.
top // [1000, 1000, 1500]
top[2] // 1500, the outlier survived every replacement
largest.size // 0
```

Each value costs one comparison against the root and, when it is admitted, one sift of `O(log k)`. Memory stays at `k` values however long the stream runs.

**Modules:** [`knotkit/heap`](/modules/heap/) · [API reference](/reference/knotkit/heap/)
