Skip to content

Kth Largest Element in an Array

Find the k-th largest number without sorting everything, using a min-heap that keeps only the top k.

MediumHeaps and Top K
Solve on LeetCode

The problem

You get an integer array nums and an integer k. Return the k-th largest element of the array, counting positions in sorted order, so repeated values count separately: in [4, 4, 1] the 2nd largest is 4. Try to solve it without sorting the whole array.

Input nums = [7, 2, 9, 4, 6], k = 2

Output 7

From largest to smallest the values are 9, 7, 6, 4, 2, and the second one is 7.

Input nums = [5, 8, 8, 1, 3], k = 3

Output 5

Both 8s count, so the order is 8, 8, 5, 3, 1 and the 3rd largest is 5.

Key constraint: Up to 100,000 values, and the challenge is to do better than sorting the whole array.

How to spot the pattern

  • You need the k-th largest value, not the full sorted order.
  • Only the top k values matter, so a small heap can stand in for sorting everything.

The idea

You don't need the whole array in order, only its k largest values. Keep them in a min-heap of size k while you scan: push each number, and when the heap grows past k, pop its smallest. After the scan the heap holds the k largest numbers, and its top, the smallest of them, is the k-th largest.

Brute force: Sort the array from largest to smallest and return the value at index k - 1, which costs O(n log n).

Step by step

  1. 1Create an empty min-heap.
  2. 2For each number, push it onto the heap.
  3. 3If the heap now holds more than k numbers, pop the smallest.
  4. 4After the loop, return the top of the heap.

See the pattern move

The heaps and top k pattern on a small example. Step through it, or press play.

Code

import heapq


class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        heap = []  # min-heap holding the k largest numbers seen so far
        for num in nums:
            heapq.heappush(heap, num)
            if len(heap) > k:
                heapq.heappop(heap)  # drop the smallest
        return heap[0]

Complexity

Time

O(n log k)

Space

O(k)

Each of the n numbers goes through a heap that never holds more than k + 1 values.

Watch out for

  • Removing duplicates first: the k-th largest counts repeated values separately.
  • Reading the k-th entry of the heap's internal array: a heap is only partly ordered, so only its top is known.
  • Getting the index off by one when sorting instead: in ascending order the answer sits at index n - k.

Follow-up questions

Can you do it in O(n) on average?

Use quickselect: partition around a pivot as in quicksort, then continue only into the side that contains index n - k. With a random pivot it runs in O(n) on average, though the worst case is O(n^2).

What if the values lie in a small range?

Count how often each value appears (here values are between -10,000 and 10,000), then walk the counts from the largest value down until you have passed k numbers. That is O(n + range).

In Hinglish

Poora sort karne ki zaroorat nahi. Size k ka min-heap rakho, k se bada ho jaaye toh sabse chhota nikaal do; aakhir mein heap ka top hi answer hai.

Related problems