KatInterview

Locate the K-th Dominant Value

Heaps, Sorting & SearchAuto-graded · 18 test cases
MediumAuto-gradedHeaps, Sorting & Searchheaps-sortingarraysquickselect

Last updated

Find the k-th largest integer in an unsorted list efficiently using quickselect or priority queues.

Given an unsorted array of integers a and an integer k, determine the $k$-th largest value present in the array.

Note that this refers to the $k$-th value when sorted in non-decreasing order ( counting duplicate values separately), rather than the $k$-th unique entry.

Constraints

  • $1 \le k \le \text{len}(a) \le 10^5$
  • $-10^4 \le a[i] \le 10^4$

Examples

Example 1

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

Output: 5

Example 2

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

Output: 4

Hints

Hint 1

Think about how finding the k-th largest element relates to finding an element at a specific index in a sorted list.

Hint 2

Full sorting takes O(n log n) time. Can you use a min-heap of size k to do better?

Hint 3

Can you apply a quickselect partitioning scheme to reach average linear time complexity?