KatInterview

Top-K Cutoff: Find the K-th Highest Value

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapsortingorder-statistics

Last updated

Tests order-statistics intuition by asking candidates to extract the k-th largest element from an unsorted array without a full sort.

Problem

You are given an unsorted list of integers and a positive integer k. Your task is to return the k-th highest value in the list.

Think of it this way: if you lined up all the values from largest to smallest (keeping every duplicate in its own position), the answer is the value sitting at position k in that line.

For example, with the list [5, 5, 4] and k = 2, position 1 holds 5, and position 2 also holds 5 — so the answer is 5, not 4. Duplicates occupy separate positions.

Input:

  • nums: an unsorted list of integers (may contain duplicates)
  • k: a positive integer, guaranteed to satisfy 1 <= k <= len(nums)

Output:

  • A single integer — the value that would appear at index k - 1 in the list sorted in descending order.

Constraints

  • 1 <= len(nums) <= 2 * 10^5
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= len(nums)
  • Duplicates count as distinct positions in the ranking.
  • You may not assume the input is sorted or free of repeated values.
  • Aim for a solution better than O(n log n) time.

Examples

Example 1

Input: kth_largest([3, 2, 1, 5, 6, 4], 2)

Output: 5

Example 2

Input: kth_largest([5, 5, 4], 2)

Output: 5

Hints

Hint 1

Sorting the whole array gives a correct but suboptimal O(n log n) answer — can you avoid sorting elements that can never be in the top k?

Hint 2

Think about what data structure lets you cheaply track the k largest values seen so far and immediately discard a value the moment you know it can't make the cut.

Hint 3

A min-heap of exactly k elements is the key. Its root is always the weakest member of your current top-k shortlist — use that root as a gatekeeper when scanning the rest of the array.