Skip to content

Kth Largest Element in Array

LeetCode #215 - Kth Largest Element in Array

Section titled “LeetCode #215 - Kth Largest Element in Array”

Solve this classic coding interview problem efficiently using multiple approaches.

numskOutputExplanation
[3,2,1,5,6,4]25Sorted: [1,2,3,4,5,6]. 2nd largest = 5
[3,2,3,1,2,4,5,5,6]44Sorted: [1,2,2,3,3,4,5,5,6]. 4th largest = 4
[1]11Single element
[7,7,7,7]27All same value
  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
ApproachTimeSpaceBest When
Min HeapO(n log k)O(k)Most cases — k is small
QuickSelectO(n)O(1)Average case optimal
Brute Force (Sort)O(n log n)O(1)Learning or small arrays
  • Pick Min Heap for a balanced, interview-ready solution.
  • Pick QuickSelect if you want the theoretical average case optimal solution.
  • Pick Brute Force if you are learning the problem from scratch.
Best For Most Cases
Min Heap
O(n log k) time · O(k) space
Optimal Average Case
QuickSelect
O(n) time · O(1) space
Simple to Learn
Brute Force
O(n log n) time · O(1) space
★ Recommended

Maintain a min heap of size k containing the k largest elements. Iterate through the array and keep only the k largest elements in the heap. The root of the heap is the kth largest.

⏱ Time O(n log k) n iterations, each O(log k) 💾 Space O(k) Heap of k elements
kth_largest_element_in_array_min_heap.py
from typing import List
def kth_largest_element_in_array_min_heap(nums: List[int]) -> int:
"""
Kth Largest Element In Array - Min Heap approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass
🎯 Interview Favourite

Use the QuickSelect algorithm (based on QuickSort partition) to find the kth largest element without fully sorting. Average time is O(n).

⏱ Time O(n) Average case 💾 Space O(1) Constant
kth_largest_element_in_array_quickselect.py
from typing import List
def kth_largest_element_in_array_quickselect(nums: List[int]) -> int:
"""
Kth Largest Element In Array - Quickselect approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass
✓ Simple

Sort the array in descending order and return the element at index k-1. Simple and straightforward for learning.

⏱ Time O(n log n) Sorting dominant 💾 Space O(1) Constant
kth_largest_element_in_array_brute_force.py
from typing import List
def kth_largest_element_in_array_brute_force(nums: List[int]) -> int:
"""
Kth Largest Element In Array - Brute Force approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass