K-th Largest Element in an Array

medium

Given an integer array arr and an integer k, return the k-th largest element (with k = 1 meaning the maximum). Note this is the k-th largest in sorted order, not the k-th distinct value. If k is out of range (k < 1 or k > the array length), return -1.

Hints

You don't need the whole sorted order — only the boundary between the top k and the rest.
Keep a min-heap holding the k largest elements seen so far.
When the heap exceeds size k, pop the smallest; the root is the k-th largest.

Common doubts

A size-k min-heap keeps the k largest and exposes their smallest (the k-th largest) at the root in O(1). A max-heap of everything would cost O(n) space and O(n log n).
When k is much smaller than n: O(n log k) vs O(n log n). For k close to n, sorting is comparable and simpler.
No — duplicates count as separate elements, matching sorted-order position k.

Interview follow-ups

The size-k min-heap works unchanged — that's the k-th-largest-in-a-stream problem.
Yes — Quickselect partitions around a pivot to place the k-th element in expected linear time.

Fun facts

  • This is LeetCode 215, one of the most-asked heap questions in interviews.
  • The size-k min-heap is the seed pattern for 'k closest', 'top-k frequent', and 'merge k lists'.

Asked at

AmazonFacebookMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: arr = [3, 2, 1, 5, 6, 4], k = 2
Output: 5
Sorted descending is [6, 5, 4, 3, 2, 1]; the 2nd largest is 5.
Example 2
Input: arr = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
Output: 4
Duplicates count: the 4th largest by value is 4.
Constraints

- 0 <= arr.length <= 10^5 - -10^9 <= arr[i] <= 10^9 - 1 <= k <= 10^5

Solve this problem →