Leetcode #215: Kth Largest Element in an Array
In this guide, we solve Leetcode #215 Kth Largest Element in an Array in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Divide and Conquer, Quickselect, Sorting, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Example
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Python Solution
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def quick_sort(l: int, r: int) -> int:
if l == r:
return nums[l]
i, j = l - 1, r + 1
x = nums[(l + r) >> 1]
while i < j:
while 1:
i += 1
if nums[i] >= x:
break
while 1:
j -= 1
if nums[j] <= x:
break
if i < j:
nums[i], nums[j] = nums[j], nums[i]
if j < k:
return quick_sort(j + 1, r)
return quick_sort(l, j)
n = len(nums)
k = n - k
return quick_sort(0, n - 1)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.