Heap / Priority Queue
Medium

Kth Largest Element in an Array

Find the kth largest element in an unsorted array.
Problem Understanding

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 the sorted order, not the kth distinct element.

Example 1:

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

Example 2:

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

We can use a Min-Heap to efficiently find the Kth largest element.

  1. Initialize a Min-Heap: We will maintain a heap of size k.
  2. Iterate through the array: For each number:
    • Push it onto the heap.
    • If the heap size exceeds k, pop the smallest element (root).
  3. Result: After processing all numbers, the heap contains the k largest elements. The smallest of these (the root) is exactly the kth largest element.

Why Min-Heap?
We want to keep the "largest" elements. By popping the smallest element whenever we exceed size K, we discard the "small" numbers and keep the "large" ones.

Interactive Visualization
Step 1 / 1
Empty Heap

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep