AAlgoLoopSpaced repetition for LeetCode
MEDIUMHeap / Priority QueueLeetCode ↗

Kth Largest Element in an Array

The key idea

You do not need the array fully sorted — you only need the boundary at rank k. A min-heap of size k keeps the k largest seen so far, with the kth largest sitting at its root. Quickselect partitions toward that rank in expected linear time.

Problem

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in sorted order, not the kth distinct element.

Can you solve it without sorting the whole array?

Constraints

Examples

Input: nums = [3,2,1,5,6,4], k = 2 Output: 5
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4

Complexity

Time: O(n log k) Space: O(k)

See the full solution

410310
Step-by-step visualization
Start free →

More Heap / Priority Queue problems