Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Kth Largest Element in a Stream
Problem
Design a class KthLargest that tracks the k-th largest value in a growing stream of integers, counting duplicates as separate entries.
KthLargest(k, nums)initializes the tracker with an integerkand an initial listnums(possibly empty).add(val)appendsvalto the stream and returns the currentk-th largest value.
It is guaranteed that by the time add is called there are at least k values in the stream.
kand the size of the initial list are each bounded by roughly ten thousand.- Values fit comfortably in a normal int, positive or negative.
- Up to about ten thousand calls to
add.
Examples
KthLargest(3, [6, 7, 10, 3]), thenadd(5)→6,add(11)→7,add(15)→10,add(12)→11,add(6)→11. Each new value that beats the current 3rd-largest bumps the threshold up.KthLargest(1, []), thenadd(-5)→-5,add(-1)→-1,add(-8)→-1. With k = 1 the tracker simply reports the running maximum.KthLargest(2, [9, 9]), thenadd(2)→9. Duplicates count separately, so the 2nd largest is the second 9.
Hints
- You only ever need to answer questions about the top
kvalues. Everything smaller is irrelevant forever. Why? - Among the top
k, which single value do you need instant access to, and which value do you need to evict when a new one arrives? - Keep a min-heap of exactly
kelements; its root is the answer, and eachaddpushes then pops if the size exceedsk.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.