InterviewPrepKit

Home / Coding / Heap & Priority Queue

Kth Largest Element in an Array

medium Original β†—
Solving tips
  • Recite the selection ladder: sort O(n log n), size-k MIN-heap O(n log k), quickselect average O(n), counting sort O(n + range) when values are tiny (here [-10^4, 10^4]).
  • For the heap, keep the k largest in a min-heap and return its root (the smallest of them); for quickselect the target ascending index is n - k.
  • Randomize the quickselect pivot and use a 3-way partition to stay linear on sorted or all-equal inputs.
  • 'K-th largest' counts duplicates, and the answer index is n - k, not k or k - 1.

Problem

Given an integer array nums and an integer k, return the k-th largest element in sorted order, counting duplicates β€” not the k-th distinct value.

The follow-up (and the point of the exercise): can you do it without fully sorting the array?

Examples

  • nums = [3, 2, 1, 5, 6, 4], k = 2 β†’ 5 β€” sorted descending: 6, 5, 4, 3, 2, 1.
  • nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 β†’ 4 β€” sorted descending: 6, 5, 5, 4, … (the two 5s each take a rank).
  • nums = [1], k = 1 β†’ 1 β€” the only element is the 1st largest.

Constraints

  • 1 <= k <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4

Think about it first

Hint 1 Sorting gives the answer in one line at O(n log n). Everything after that is about noticing you asked for one element, not a full ordering.
Hint 2 Sweep the array once keeping only the k largest values seen so far in a min-heap; the root is the current k-th largest. What does each element cost, and when is that a win over sorting? Also: look at how tight the value range is compared to n.
Hint 3 Two O(n)-flavored routes: quickselect (partition around a pivot, recurse into the side holding index nβˆ’k) for average O(n), or counting sort over the 2Β·10^4-wide value range β€” count occurrences, then walk from the top subtracting counts until k is used up.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.