← Questions
Top K largest distinct values
0
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, last asked Mar 2026. It tests heaps and sorting.
Given an integer array that may contain repeated values, return the k largest distinct values, largest first.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
top_k_distinct(nums: list[int], k: int) -> list[int]— if there are fewer thankdistinct values, return all of them.
Example
top_k_distinct([3, 1, 3, 5, 5, 2], 2) -> [5, 3] # 5 and 3 each count once
top_k_distinct([4, 4, 4], 3) -> [4]
top_k_distinct([], 1) -> []
Constraints
- Up to 10^6 elements; values fit in 32-bit integers;
1 <= k <= 10^5.
Clarifying questions
- Should the output be sorted? Largest first?
- What if there are fewer than
kdistinct values? - Is
ksmall compared withn? - Is the input a fixed array or a stream?
What a strong answer covers
- Dedupe with a set, then sort:
O(n + d log d)forddistinct values. - Better when
kis small: a min-heap of sizekover the distinct values,O(n + d log k), with a set so duplicates never enter the heap twice. - Quickselect on the distinct values for expected
O(n), then sort thekresults. - The trap: a heap over the raw array without deduping returns repeated values.
- Tests: all equal, fewer distinct values than
k, negative values,k = 1.
Follow-ups
- The input is a stream: keep the
klargest distinct values seen so far in bounded memory. - Return the
kmost frequent values instead. - The data is spread over many machines.
Where it's asked
- Google · Onsite coding · Last asked Mar 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)
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
