#215

Kth Largest Element in an Array

Medium
ArrayDivide and ConquerSortingHeap (Priority Queue)QuickselectHeapSortingQuickselect
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n log n)
O(n log k)
Space
O(1)
O(k)
💡

Intuition

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

We can find the k-th largest element without fully sorting the array using a min-heap. By maintaining a heap of size k, we can efficiently track the largest k elements.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a min-heap of size k.
  2. 2Step 2: Iterate through the array, adding elements to the heap.
  3. 3Step 3: If the heap exceeds size k, remove the smallest element (the root of the heap).
  4. 4Step 4: After processing all elements, the root of the heap is the k-th largest element.
solution.py5 lines
1# Full working Python code
2import heapq
3
4def findKthLargest(nums, k):
5    return heapq.nlargest(k, nums)[-1]

Complexity note: Maintaining a heap of size k takes O(log k) time for each of the n elements, resulting in O(n log k) overall. We use O(k) space for the heap.

  • 1Using a heap allows us to efficiently track the largest elements without sorting the entire array.
  • 2The k-th largest element can be found in linear time using Quickselect, which is another optimal approach.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.