Implement k-th largest in a number stream
ZillowMachine Learning Engineer · Technical ScreenLast updated
This question evaluates proficiency with data structures and order-statistics in a streaming context, focusing on API design and time/space complexity trade-offs within the Coding & Algorithms domain.
You are designing a small library to monitor statistics over a stream of integers.
Implement a data structure that, given an integer k and an initial list of integers, supports the following operation:
add(val): insert the integervalinto the stream and return the k-th largest element among all elements seen so far (including the new one).
More formally, after each call to add, if you took all numbers that have been provided (both the initial list and all numbers added so far), sorted them in non-decreasing order, you should return the element that is k positions from the end (the k-th largest). You may assume that k is always valid (i.e., there are at least k elements after each add call).
API to implement
Define a class or type with:
-
A constructor that takes:
-
k(an integer) -
nums(a list/array of integers, possibly empty) -
A method:
-
add(val: int) -> intthat insertsvaland returns the current k-th largest element.
Constraints
- You may assume:
1 \le k \le 10^4- At most
10^4calls toaddwill be made. - Each integer value fits in a standard 32-bit signed integer.
- Your design should be efficient enough to handle the worst-case number of
addcalls within typical interview time complexity expectations.
Describe only the code-level behavior and interface; you do not need to provide a working implementation here.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.