Back to Practice
#0236

Kth Largest Element

MediumDSA28 min20 XP

Problem

Given nums and k, return the kth largest element. Use a min-heap of size k.

Why This Matters

Top-k problems are everywhere in search, recommendations, metrics dashboards, and stream processing.

Function Signature

def kth_largest(nums, k):

Examples

Example 1
Inputnums = [3, 2, 1, 5, 6, 4], k = 2
Output5

The sorted order descending is 6, 5, 4, 3, 2, 1, so the 2nd largest is 5.

Constraints

  • Return the exact requested value.
  • Handle empty or small inputs when the prompt allows them.
  • Prefer the target DSA pattern over brute force when the input can grow.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Second largest
Input[3, 2, 1, 5, 6, 4], k = 2
Expected5

The heap keeps the two largest values seen so far.

Duplicates included
Input[3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
Expected4

Duplicates count as separate elements.

Hidden Test Categories
k equals 1k equals len(nums)negative values