K-th greatest value in every growing prefix
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round and at Netflix, last asked Feb 2026. It tests heap, streaming and order statistics.
You are given arr, a permutation of the integers 1 to n (each value appears exactly once), and an integer k with 1 <= k <= n.
Read arr from left to right. After reading each prefix of length i, for every i from k to n, report the k-th greatest value in that prefix. Return the n - k + 1 answers in order.
def kth_greatest_in_prefixes(arr: list[int], k: int) -> list[int]: ...
Constraints
1 <= n <= 10^5-
arris a permutation of1..n 1 <= k <= n
Example 1
arr = [3, 1, 4, 2, 5], k = 2
output: [1, 3, 3, 4]
Prefix [3, 1]: the 2nd greatest value is 1. Add 4 to get [3, 1, 4]: the answer is 3. Add 2: still 3. Add 5: the top two are 5 and 4, so the answer is 4.
Example 2
arr = [4, 3, 2, 1], k = 1
output: [4, 4, 4, 4]
With k = 1 the answer is the running maximum.
Aim for better than sorting every prefix. Then say whether the fact that arr is a permutation lets you do better still.
Clarifying questions
- Is the output for prefix lengths
k..nonly, so it hasn - k + 1entries? - With
k = n, is the single answer the minimum of the whole array? - If the values were not a permutation, could there be duplicates, and how would ties count?
- Is
nlarge enough that O(n log k) matters compared with O(n)?
What a strong answer covers
- Keeps a min-heap of the
klargest values seen so far. The heap's top is the answer. Each new value replaces the top when it is larger. That is O(n log k) time and O(k) memory. - Notices that the answer never decreases as the prefix grows.
- Uses the permutation: values are
1..n, so a presence array plus a pointer that only moves up gives an amortized O(n) solution. - Explains why sorting each prefix (O(n^2 log n)) is far too slow for
n = 10^5. - Tests
k = 1(the running maximum),k = n, a sorted array and a reversed array.
Follow-ups
- Arbitrary integers with duplicates.
- A sliding window instead of a growing prefix: values also leave, so use a Fenwick tree or an order-statistics tree.
- A different
kfor each query. - A stream with no known length or value range.
Where it's asked
- Google · Onsite coding · Last asked Feb 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
- Netflix
What it tests
heap · streaming · order statistics
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.

