← DSA
MEDIUM

Kth Largest Element in an Array

PracticeNeetCode ↗LeetCode ↗

Given an integer array nums and an integer k, return the kth largest element in sorted order — not the kth distinct value, so duplicates count separately.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Create an empty min-heap.
  2. For each number in nums, push it onto the heap.
  3. If the heap's size exceeds k, pop the smallest element.
  4. After the array is fully processed, return the heap's root.

Complexity

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

Code

import heapq

def findKthLargest(nums: list[int], k: int) -> int:
    heap = []
    for n in nums:
        heapq.heappush(heap, n)
        if len(heap) > k:
            heapq.heappop(heap)
    return heap[0]

Code Explanation

How the solution above works, piece by piece.

  1. Keep a min-heap of the k largest values seen so far.
  2. Push each number; if the heap has more than k items, pop the smallest.
  3. What's left are the k largest numbers, and the smallest of them, heap[0], is the k-th largest.
  4. O(n log k) time and O(k) space, better than sorting (O(n log n)) when k is small.

Visual Walkthrough

Running it on nums = [3, 2, 1, 5, 6, 4], k = 2:

trace3push 3size ≤ 2, keep23push 2size ≤ 2, keep23push 1pop 135push 5pop 256push 6pop 356push 4pop 4 → heap[0] = 5
With k = 2 the heap never holds more than two numbers. After the last push it holds 5 and 6, so the 2nd largest is 5.
heap minimum

Video Explanation

NeetCode — Quick Select, LeetCode 215