← Back to problems
UNSW COMP2521 · hard

Heap: k-th Largest

Heap: k-th Largest

Given n integers and k, print the k-th largest value (duplicates rank by value).

Classic: keep a min-heap of size k; after scanning, its root is the k-th largest — O(n log k). Or just sort descending and take index k-1.

Input: line 1 n k; line 2 n integers. Output: the k-th largest value.

Example: 6 2 / 3 1 5 2 4 6 -> 5.