---
title: k-th largest in a stream
url: https://gurkanozkan.ai/learn/coding/mle-k-th-largest-in-a-stream-29/
markdown: https://gurkanozkan.ai/learn/coding/mle-k-th-largest-in-a-stream-29.md
kind: coding
difficulty: Easy
topics:
  - Heaps
  - Streaming
json: https://gurkanozkan.ai/api/learn/coding/mle-k-th-largest-in-a-stream-29.json
robots: noindex
---

# k-th largest in a stream

Start from the values in `initial`. After inserting each value of `adds` (in order), report the k-th largest value seen so far, counting duplicates separately, or `None` if fewer than `k` values have been seen.

## Signature

```python
def kth_largest_stream(k: int, initial: list[int], adds: list[int]) -> list[int | None]: ...
```

## Examples

Each call and the value it should give.

```python
>>> kth_largest_stream(3, [4, 5, 8, 2], [3, 5, 10, 9, 4]) == [4, 5, 5, 8, 8]
True

>>> kth_largest_stream(1, [], [-1, 1, -2]) == [-1, 1, 1]
True
```

## Hints

1. Keep a min-heap capped at k values; O(log k) per insert.
2. After each add, report the heap root (the k-th largest) or None if fewer than k exist.
3. Count duplicates separately — not the k-th distinct value.

## Reference solution

```python
import heapq

def kth_largest_stream(k, initial, adds):
    h = []
    def push(x):
        heapq.heappush(h, x)
        if len(h) > k:
            heapq.heappop(h)
    for x in initial:
        push(x)
    out = []
    for x in adds:
        push(x)
        out.append(h[0] if len(h) == k else None)
    return out
```

## What a strong solution covers

- Min-heap capped at size k, O(log k) per insert.
- Handles fewer than k values.
- Discusses top-k with deletions and approximate heavy hitters (Count-Min sketch).

## Common mistakes

- a max-heap holding all values (O(n) memory)
- returning the k-th distinct value.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
