KatInterview

Pick the Rank-k Score From the Top

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchquickselectheapselection

Last updated

Select the k-th largest value, counting duplicates separately, from an unsorted integer list without a full sort, using quickselect or a bounded heap.

Pick the Rank-k Score From the Top

You are given a list of integers scores (unsorted) and an integer k. Return the value that would be in position k if the scores were arranged from largest to smallest, where position 1 is the largest.

Rules

  • Duplicates count separately. In [5, 5, 4], the 1st largest is 5, the 2nd largest is 5, and the 3rd largest is 4. You are not looking for the k-th distinct value.
  • Equivalently, the answer is the element at index len(scores) - k of the list sorted in ascending order.
  • Do not modify the caller's list.
  • Aim to avoid sorting the entire list. A randomized partition-based selection (expected linear time) or a min-heap capped at size k (O(n log k) time) are the usual approaches. Only the returned value is checked.

Input

  • scores: a list of n integers (may include negative values and repeated values).
  • k: an integer with 1 <= k <= n.

Output

  • A single integer: the k-th largest value in scores.

Constraints

  • 1 <= k <= n = len(scores)
  • Values are integers and may be negative or repeated.
  • k = 1 yields the maximum and k = n yields the minimum.
  • A single-element list returns that element.

Examples

Example 1

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

Output: 5

Example 2

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

Output: 4

Example 3

Input: kth_largest_score([-1, -1], 1)

Output: -1

Hints

Hint 1

Sort order tells you where the answer lives: the k-th largest sits at ascending index n - k. You only need the one element that belongs at that index, not the entire sorted order.

Hint 2

Quickselect: partition around a random pivot, then continue only into the side that contains the target index. A three-way split (less, equal, greater) handles many duplicates cleanly, and if the target index falls in the equal block you are done.

Hint 3

Heap alternative: keep a min-heap holding the k largest values seen so far. When it grows past k, drop the smallest. After one pass, the root of the heap is the k-th largest.