Kth Largest Element in an Array (LeetCode 215): Solution and Explanation

Medium
Array
Divide And Conquer
Sorting
Heap
Quickselect

Given an unsorted array of integers and a number k, return the value that would sit in position k if the array were sorted from largest to smallest. Duplicates count separately, so this is not the k-th distinct value.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Sorting the array and reading nums[len(nums) - k] gives the answer in O(n log n), and in an interview it is a fine opening move. The follow-up is always whether you can avoid sorting everything, since you only care about one position.

Think about what you would need to remember if the numbers arrived one at a time. You only have to track the k largest values seen so far. The k-th largest overall is then the smallest of those k. Any new number smaller than that smallest one cannot affect the answer, and any bigger number pushes the current smallest out of the group.

A min heap capped at size k models this exactly. Its top is the smallest of the kept values, which is both the current k-th largest and the value to evict when something bigger comes along. The reference code simply pushes every number and pops the top whenever the size exceeds k. Pushing first and then popping handles both cases at once: if the new number is small, it is the one that gets popped right back out.

After the scan the heap holds the k largest numbers in the array, so its top, heap[0], is the answer. Because the heap never grows beyond k + 1, each operation costs O(log k), which is much cheaper than sorting when k is small.

Approach: Min heap of size k

  1. Create an empty list heap to use with heapq.
  2. For each number, push it onto the heap.
  3. If the heap size is now greater than k, pop the smallest value, since it cannot be among the k largest.
  4. After the loop the heap holds exactly the k largest values.
  5. Return heap[0], the smallest of those, which is the k-th largest overall.

Step-by-step example

nums = [3,2,1,5,6,4], k = 2
  1. Push 3, then 2. The heap holds {2,3} and its size equals k.
  2. Push 1, so the size is 3. Pop the minimum, 1. The heap holds {2,3}.
  3. Push 5 and pop the minimum, 2. The heap holds {3,5}.
  4. Push 6 and pop 3. The heap holds {5,6}.
  5. Push 4 and pop 4 right back out, since it is the smallest. The heap still holds {5,6}.
  6. The top of the heap is 5, so the second largest element is 5.

Code: Python, Java, C++

1class Solution:
2    def findKthLargest(self, nums: List[int], k: int) -> int:
3        # Use min heap of size k
4        heap = []
5
6        for num in nums:
7            heapq.heappush(heap, num)
8            if len(heap) > k:
9                heapq.heappop(heap)
10
11        return heap[0]

Time and space complexity

Time

O(n log k)

Each of the n numbers is pushed once and popped at most once, and the heap holds at most k + 1 items, so every operation costs O(log k).

Space

O(k)

The heap never stores more than k + 1 values.

Other approaches

Quickselect (time O(n) average, space O(1))

Partition the array around a random pivot so larger values sit on one side, then continue only into the side that contains the target position. Each step throws away a chunk of the array, so the expected work is linear, though a run of bad pivots can make it quadratic.

Sort the array (time O(n log n), space O(n))

Sort ascending and return nums[len(nums) - k]. It is the simplest solution and fine when performance is not the point of the question.

Common mistakes

  • Using a max heap of all n elements and popping k times. It is correct but costs O(n + k log n) time and O(n) space.
  • Deduplicating the input, for example with a set. The problem counts duplicates, so in [3,3,2] the second largest is 3, not 2.
  • Returning heap[-1] instead of heap[0]. A heap is only ordered at the root, so the last list element is not the maximum or the minimum in general.
  • Off-by-one in the sorted version, such as nums[k] or nums[len(nums) - k - 1] after sorting ascending.

Frequently asked questions

Why use a min heap to find the kth largest element?

You keep the k largest values seen so far, and the one you need to compare against and evict is the smallest of them. A min heap puts exactly that value on top, and at the end it is the answer.

Can you find the kth largest element without sorting?

Yes. A size-k heap does it in O(n log k), and quickselect does it in O(n) on average by partitioning and recursing into one side only.

Is quickselect better than a heap?

Quickselect has a better average time and uses no extra memory, but it reorders the array and has an O(n²) worst case. The heap is predictable and also works on streaming data.