← Questions

K-th greatest value in every growing prefix

0
GoogleNetflixCodingLast asked Feb 2026

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
  • arr is a permutation of 1..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..n only, so it has n - k + 1 entries?
  • 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 n large enough that O(n log k) matters compared with O(n)?

What a strong answer covers

  • Keeps a min-heap of the k largest 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 k for 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding