Browse Curriculum
FAANGPrep Sprint
Medium

Kth Largest Element in an Array

Find the kth largest element in an unsorted array.
10 min read
Time: O(n)
Space: O(1)
Solve on LeetCode

Problem Understanding

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

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

Example 2:

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

Algorithm Strategy

We can use a Min-Heap to efficiently find the Kth largest element.

  1. Initialize a Min-Heap: We will maintain a heap of size k.
  2. Iterate through the array: For each number:
    • Push it onto the heap.
    • If the heap size exceeds k, pop the smallest element (root).
  3. Result: After processing all numbers, the heap contains the k largest elements. The smallest of these (the root) is exactly the kth largest element.

Why Min-Heap?
We want to keep the "largest" elements. By popping the smallest element whenever we exceed size K, we discard the "small" numbers and keep the "large" ones.

Interactive Visualization

Step 1 / 1
Empty Heap

Initializing...

1x

Watch how the Min-Heap maintains the top K elements.

Dry Run

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

Step Num Action Heap Size Comment
1 3 Push 3 [3] 1
2 2 Push 2 [2, 3] 2 Min-Heap property (2 < 3)
3 1 Push 1 [1, 3, 2] 3 Size > k (3 > 2), Pop Min (1)
4 - Pop 1 [2, 3] 2 Heap holds largest so far
5 5 Push 5 [2, 3, 5] 3 Size > k, Pop Min (2)
6 - Pop 2 [3, 5] 2
7 6 Push 6 [3, 5, 6] 3 Size > k, Pop Min (3)
8 - Pop 3 [5, 6] 2
9 4 Push 4 [4, 6, 5] 3 Size > k, Pop Min (4)
10 - Pop 4 [5, 6] 2
End - Root is Ans 5 - 5 is the 2nd largest

Edge Cases

  • k = 1: Equivalent to finding the maximum element.

  • k = N: Equivalent to finding the minimum element.

  • Array limits: Ensure heap handles duplicate values correctly.

Solution

Min-Heap implementation.

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

Complexity Analysis

  • Time Complexity: O(N log K)
    • We iterate through N elements.
    • For each element, we perform a heap push/pop operation, which takes O(log K) time (since the heap size is limited to K).
    • Total time: N * log K.
  • Space Complexity: O(K)
    • The heap stores only K elements.