Topic · HeapMedium
Kth Largest Element in an Array
Understand the problem
Given an array nums and an integer k, return the kth largest element in the array (by sorted order, NOT the kth distinct element — duplicate values still count at each position).
Examples:
ts
nums = [3, 2, 1, 5, 6, 4], k = 2
output = 5 // sorted descending: 6, 5, 4, 3, 2, 1 → the 2nd is 5
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
output = 4 // sorted descending: 6, 5, 5, 4, ... → the 4th is 4The classic follow-up: "can you do it WITHOUT sorting the whole array?" — that is where the heap comes in.
Basic approach
O(n log n) time, O(n) spacets
function findKthLargest(nums: number[], k: number): number {
const sorted = [...nums].sort((a, b) => b - a) // sort descending
return sorted[k - 1]
}Why this approach is slow:
Sorting the whole array just to read one position is wasted work when k is much smaller than n (for example, the top 10 out of 1 million elements).
Interviewers usually accept this as an opening step and then ask for an optimization.
Unlock the optimal solution, the step-by-step trace and related questions
See the full step-by-step trace, Big-O and edge cases.