- Interview Questions
- /
- Problems
- /
- Kth Largest Element in an Array
Kth Largest Element in an Array
Return the value that would sit in position k if the array were sorted from largest to smallest. Heaps get O(n log k); quickselect gets O(n) on average. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
Given an integer array nums and an integer k, return the k-th largest value in the array.
This means the k-th largest by position in sorted order, not the k-th largest distinct value: in [6, 6, 3], both the first and second largest are 6.
Try to do better than sorting the whole array.
Example 1
- Input
- nums = [7, 2, 9, 4, 5], k = 2
- Output
- 7
From largest to smallest the values are 9, 7, 5, 4, 2. The second is 7.
Example 2
- Input
- nums = [6, 6, 3, 6, 1], k = 3
- Output
- 6
Sorted descending: 6, 6, 6, 3, 1. Repeated values each take a position.
Constraints
- 1 ≤ k ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
Practice
Runs 12 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Kth Largest Element in an Array in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Kth Largest Element in an Array
Pattern: Quickselect
Sorting answers the question, but it does far more work than needed: it puts every element in place when you only care about one position. The k-th largest is the element at index n - k of the ascending sort, so the real question is "which value lands at index n - k?"
Quicksort's partition step answers part of that for free. After partitioning around a pivot, everything smaller is on the left and everything larger is on the right, so you know exactly which side contains index n - k. Recurse into that side only and ignore the other. On average each round throws away a constant fraction of the array, so the total work is n + n/2 + n/4 + … = O(n).
Two details keep it fast in practice: pick the pivot at random, so sorted input doesn't trigger the O(n²) worst case, and partition into three groups (less, equal, greater), so arrays full of duplicates don't either.
Approach 1: Sort
Sort ascending and return nums[n - k]. One line and hard to get wrong, which makes it a fine opening answer, but it is O(n log n).
Time O(n log n) · Space O(1) to O(n), depending on the sort
Approach 2: Min-heap of size k
Keep the k largest values seen so far in a min-heap. For each new value, push it, and if the heap has more than k items, pop the smallest. The heap's top is the answer. Good when k is small or the data arrives as a stream.
Time O(n log k) · Space O(k)
Approach 3: Quickselect with a random pivot
Let target = n - k, and work on the range [lo, hi], starting with the whole array.
- Pick a random pivot value from the range.
- Partition the range into three parts with one pass (the Dutch national flag scheme):
< pivot,== pivot,> pivot. Call the boundaries of the middle partltandgt. - If
target < lt, continue on the left part. Iftarget > gt, continue on the right part. Otherwise the pivot is the answer.
The three-way split matters: with a two-way split, an array of identical values never shrinks and quickselect degrades to O(n²).
Time O(n) average, O(n²) worst case · Space O(1)
| Approach | Time | Space |
|---|---|---|
| Sort | O(n log n) | O(1) to O(n), depending on the sort |
| Min-heap of size k | O(n log k) | O(k) |
| Quickselect with a random pivot | O(n) average, O(n²) worst case | O(1) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Kth Largest Element in an Array solution in Python
import random
def find_kth_largest(nums: list[int], k: int) -> int:
target = len(nums) - k # index of the answer in ascending order
lo, hi = 0, len(nums) - 1
while True:
pivot = nums[random.randint(lo, hi)]
# Partition nums[lo..hi] into < pivot, == pivot, > pivot.
lt, i, gt = lo, lo, hi
while i <= gt:
if nums[i] < pivot:
nums[lt], nums[i] = nums[i], nums[lt]
lt += 1
i += 1
elif nums[i] > pivot:
nums[i], nums[gt] = nums[gt], nums[i]
gt -= 1
else:
i += 1
if target < lt:
hi = lt - 1
elif target > gt:
lo = gt + 1
else:
return pivotKth Largest Element in an Array solution in JavaScript
function findKthLargest(nums, k) {
const target = nums.length - k; // index of the answer in ascending order
let lo = 0;
let hi = nums.length - 1;
while (true) {
const pivot = nums[lo + Math.floor(Math.random() * (hi - lo + 1))];
// Partition nums[lo..hi] into < pivot, == pivot, > pivot.
let lt = lo;
let i = lo;
let gt = hi;
while (i <= gt) {
if (nums[i] < pivot) {
[nums[lt], nums[i]] = [nums[i], nums[lt]];
lt++;
i++;
} else if (nums[i] > pivot) {
[nums[i], nums[gt]] = [nums[gt], nums[i]];
gt--;
} else {
i++;
}
}
if (target < lt) hi = lt - 1;
else if (target > gt) lo = gt + 1;
else return pivot;
}
}Common mistakes
- Mixing up k-th largest with k-th smallest; the target index in ascending order is n − k, not k − 1.
- Always picking the first or last element as the pivot, which makes sorted input quadratic.
- Using a two-way partition, which never makes progress on an array of identical values.
- Using a max-heap of all n elements and popping k times, which is O(n + k log n) and misses the point of keeping the heap at size k.
- De-duplicating the values first; repeated values each count as their own position.
What interviewers look for
Give the sort answer first and say its cost, then offer the heap and quickselect as the two improvements, with their trade-offs: the heap is O(n log k), simple, and works on streams; quickselect is O(n) on average but mutates the array and has a quadratic worst case.
Interviewers usually want to hear why quickselect is linear on average (each step keeps roughly half), and how you defend against the worst case (random pivot, three-way partition). If you code quickselect, state the invariant of the partition loop before writing it; that's where the bugs are.
Follow-up questions
Can you guarantee O(n) in the worst case?
Yes, with median-of-medians pivot selection: split into groups of five, take each group's median, and recursively find the median of those to use as the pivot. It guarantees a constant fraction is discarded each round, but the constant factor is large, so random pivots are faster in practice.
What if the numbers arrive as a stream and you need the k-th largest after each one?
Keep a min-heap of size k. Each new value is pushed, and if the heap grows past k, the smallest is popped. The top is the current k-th largest, at O(log k) per update.
What if the values are small integers in a known range?
Count them. With values in -10⁴..10⁴, a counting array of size 20001 lets you walk down from the largest value, subtracting counts until you reach k. That is O(n + range) with no comparisons.
Companies that ask Kth Largest Element in an Array
Kth Largest Element in an Array is tagged by 122 companies in our interview dataset. The score shows how often it comes up at each company.
- Slalom100%
- Sumup100%
- Mozilla100%
- Pocket Gems100%
- Avito95.6%
- Coffee Meets Bagel94%
- Meta93.3%
- Texas Instruments88.2%
- Northrop Grumman85%
- Spotify84.7%
- Chamberlain Group84%
- Klarna81%
- Toyota Usa81%
- Carvana79%
- Gartner79%
- Amperity76%
- Global Payments74%
- Here Technologies73%
- Mitsubishi73%
- Palantir72%
- Apptronik72%
- Chronosphere72%
- Traveloka71%
- Affinipay71%
and 98 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required