← Questions

Top K largest distinct values

0
GoogleCodingLast asked Mar 2026

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 than k distinct 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 k distinct values?
  • Is k small compared with n?
  • 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) for d distinct values.
  • Better when k is small: a min-heap of size k over 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 the k results.
  • 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 k largest distinct values seen so far in bounded memory.
  • Return the k most 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

heaps · sorting

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