The k largest numbers in Java

Java interview exercise on Collections, difficulty 2 of 3. Solve it in the editor beside a worked example; the tests run the moment you do.

Write topK(nums, k) that returns the k largest numbers in descending order, keeping only k numbers in memory at a time: a min-heap (PriorityQueue) of size k whose smallest element is dropped whenever a bigger number arrives. If k is larger than the list, return everything sorted descending; k = 0 gives an empty list.

Each exercise pairs a worked example with a twin problem to solve in a real editor; the tests run the moment you do. Progress is saved in your browser, and in your account if you sign in.

More Collections in Java

All Java exercises · Other languages and frameworks