15% off all plans & roadmaps Use code
See plansKth Largest Element in an Array
- LeetCode 215
- Medium
- Heap (Priority Queue) Patterns
- Top K Elements (Selection/Frequency)
Updated
TL;DR: Find the kth largest value in an unsorted array, counting duplicates. Sorting works in O(n log n), a size-k min-heap gives O(n log k), and quickselect gives O(n) on average.
Problem
Given an integer array nums and an integer k, return the kth largest element of the array.
The answer is the kth largest in sorted order. It is not the kth distinct value, so duplicates each take a position.
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
Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Constraints that matter
- n up to 10^5 means O(n^2) is too slow. Scanning for the maximum k times can hit about 10^10 operations when k is near n.
- n up to 10^5 keeps O(n log n) sorting comfortably fast. A full sort is a valid answer here, and the interview question is whether you can do better.
- k is at least 1 and at most n, so the answer always exists. You never need to handle k larger than the array.
- Values are bounded by 10^4 in absolute value, so int arithmetic never overflows. The small range also allows a counting approach, though the general techniques do not rely on it.
- Duplicates are allowed and each counts, so any method that deduplicates first gives wrong answers.
Hints
Hint 1
This is a selection problem.
Hint 2
Sort the array and read the answer off by position.
Solution
Intuition
This is a selection problem. You need one element defined by its rank, not the whole sorted order. Whenever a problem asks for the kth best, the kth smallest, or the top k of something, think Top K Elements with a heap, or partition-based selection.
Picture a row of people sorted by height where you only need whoever stands at one specific spot. The pivot is the person you call out, and the group that cannot hold your spot walks away.
Sorting does more work than needed. It orders all n values, yet you only care where one rank boundary falls. Two ideas avoid the extra work. Keep only the k largest values seen so far, or split the array around a pivot and keep only the side that holds your rank.
The first idea uses a min-heap of size k. The heap holds the k largest values seen so far, and its root is the smallest of them. That root is exactly the kth largest once every value has been seen. A new value that is not bigger than the root cannot help, and a bigger one evicts the root.
The second idea is quickselect. Pick a pivot, split the array into smaller, equal and larger parts, and see which part contains the target position. Throw away the other parts. Each round shrinks the search range, and on average the total work is a geometric series that sums to O(n).
Worked example
Input: nums = [3, 2, 1, 5, 6, 4], k = 2 Output: 5 Explanation: Sorted in descending order the array is 6, 5, 4, 3, 2, 1. The largest is 6 and the second largest is 5, so the answer is 5.
Approach 1: Sort, then index
Sort the array and read the answer off by position. After an ascending sort, the largest element sits at index n - 1, the second largest at n - 2, and the kth largest at index n - k.
This is the version a beginner writes first. It is correct, short, and handles duplicates for free because every copy keeps its own slot.
Steps
- Sort
numsin ascending order. - Compute the index
n - kwherenis the array length. - Return the value at that index.
Dry run
Start with [3, 2, 1, 5, 6, 4] and k = 2.
- Sorted ascending:
[1, 2, 3, 4, 5, 6]. n = 6, so the target index is6 - 2 = 4.- The value at index 4 is
5, which matches the expected output.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(1) extra for an in-place sort, or O(n) if the sort copies |
Here n is the array length. Comparison sorting costs O(n log n) comparisons, and the final lookup is O(1). The sort works in place in most languages, so the extra memory is a small constant for the Go, Java and C# sorts. Some library sorts use O(n) or O(log n) scratch space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
# ascending order, so the kth largest is k places from the end
return nums[len(nums) - k]
JavaTested in our runner
import java.util.*;
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
// ascending order, so the kth largest is k places from the end
return nums[nums.length - k];
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
// ascending order, so the kth largest is k places from the end
return nums[nums.size() - k];
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findKthLargest = function(nums, k) {
// the comparator is required: the default sort compares as strings
nums.sort((a, b) => a - b);
return nums[nums.length - k];
};
GoTested in our runner
import "sort"
func findKthLargest(nums []int, k int) int {
sort.Ints(nums)
// ascending order, so the kth largest is k places from the end
return nums[len(nums)-k]
}
C#Tested in our runner
public class Solution {
public int findKthLargest(int[] nums, int k) {
Array.Sort(nums);
// ascending order, so the kth largest is k places from the end
return nums[nums.Length - k];
}
}

Solution pattern
Top K Elements (Selection/Frequency)
Part of Heap (Priority Queue) Patterns
Approach 2: Min-heap of size kTop K Elements (Selection/Frequency)
What's slow: sorting orders all n values, including the n - k small ones you will never return. That is wasted work, and it also forces you to hold the whole array in sorted form.
The insight that fixes it: keep a min-heap that holds only the k largest values seen so far. The root of a min-heap is its smallest element, so the root is the weakest member of the current top k. Push each value, and when the heap grows to k + 1 elements, pop the root. After the last value, the root is the kth largest.
Each push or pop costs O(log k) because the heap never holds more than k + 1 items.
Steps
- Create an empty min-heap.
- For each value
xinnums, pushxonto the heap. - If the heap now holds more than
kelements, pop the smallest one. - After the loop, the heap holds the
klargest values. - Return the root of the heap, which is the smallest of those
kvalues.
Dry run
Run [3, 2, 1, 5, 6, 4] with k = 2. The heap is shown as a sorted set for readability.
| Value | After push | Size over k? | After pop |
|---|---|---|---|
| 3 | {3} | no | {3} |
| 2 | {2, 3} | no | {2, 3} |
| 1 | {1, 2, 3} | yes, pop 1 | {2, 3} |
| 5 | {2, 3, 5} | yes, pop 2 | {3, 5} |
| 6 | {3, 5, 6} | yes, pop 3 | {5, 6} |
| 4 | {4, 5, 6} | yes, pop 4 | {5, 6} |
The heap ends as {5, 6}. Its root is 5, which is the answer.
Complexity
| Time | O(n log k) |
|---|---|
| Space | O(k) |
Here n is the array length and k is the rank. Every element causes one push and at most one pop, and each costs O(log k) because the heap holds at most k + 1 elements. That gives n * O(log k) in total. The heap never exceeds k + 1 entries, so the extra space is O(k).
PythonTested in our runner
import heapq
from typing import List, Optional
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap: List[int] = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
# evict the smallest, it cannot be in the top k
heapq.heappop(heap)
return heap[0]
JavaTested in our runner
import java.util.*;
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
for (int x : nums) {
heap.add(x);
if (heap.size() > k) {
// evict the smallest, it cannot be in the top k
heap.poll();
}
}
return heap.peek();
}
}
C++Tested in our runner
#include <vector>
#include <queue>
#include <functional>
using namespace std;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
// greater<int> turns the default max-heap into a min-heap
priority_queue<int, vector<int>, greater<int>> heap;
for (int x : nums) {
heap.push(x);
if ((int)heap.size() > k) {
// evict the smallest, it cannot be in the top k
heap.pop();
}
}
return heap.top();
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findKthLargest = function(nums, k) {
// JavaScript has no built-in heap, so keep a small array-backed min-heap
const h = [];
const up = (i) => {
while (i > 0) {
const p = (i - 1) >> 1;
if (h[p] <= h[i]) break;
[h[p], h[i]] = [h[i], h[p]];
i = p;
}
};
const down = (i) => {
const n = h.length;
while (true) {
let s = i;
const l = 2 * i + 1;
const r = l + 1;
if (l < n && h[l] < h[s]) s = l;
if (r < n && h[r] < h[s]) s = r;
if (s === i) break;
[h[s], h[i]] = [h[i], h[s]];
i = s;
}
};
for (const x of nums) {
h.push(x);
up(h.length - 1);
if (h.length > k) {
// pop the root: move the last item to the top and sift it down
const last = h.pop();
if (h.length > 0) {
h[0] = last;
down(0);
}
}
}
return h[0];
};
GoTested in our runner
import "container/heap"
type minIntHeap []int
func (h minIntHeap) Len() int { return len(h) }
func (h minIntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h minIntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minIntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *minIntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
func findKthLargest(nums []int, k int) int {
h := &minIntHeap{}
for _, x := range nums {
heap.Push(h, x)
if h.Len() > k {
// evict the smallest, it cannot be in the top k
heap.Pop(h)
}
}
return (*h)[0]
}
C#Tested in our runner
public class Solution {
public int findKthLargest(int[] nums, int k) {
// PriorityQueue<TElement, TPriority> is a min-heap on priority
var heap = new PriorityQueue<int, int>();
foreach (int x in nums) {
heap.Enqueue(x, x);
if (heap.Count > k) {
// evict the smallest, it cannot be in the top k
heap.Dequeue();
}
}
return heap.Peek();
}
}
Approach 3: QuickselectOptimal
What's slow: the heap still touches every element with a log k cost, and it needs O(k) memory. When k is close to n, log k is about log n, so you gain almost nothing over sorting.
The insight that fixes it: you only need to know which element lands at one sorted position, namely index n - k in ascending order. Pick a random pivot and split the range into three parts: smaller than the pivot, equal to it, and larger. If the target index falls in the equal part, the pivot is the answer. Otherwise the target lies in exactly one other part, so you discard the rest and repeat on it.
The three-way split matters. With many duplicates, a two-way split can leave the range almost unchanged, and the work degrades. Equal values are placed once and never revisited. A random pivot makes the expected total work linear.
Why it is correct. The invariant is that the target index always stays inside the current range from lo to hi. Partitioning puts every value below the pivot before the equal zone and every larger value after it. So the element at the target position must lie in whichever zone contains that index.
Steps
- Set
lo = 0,hi = n - 1andtarget = n - k. - Pick a random index in
[lo, hi]and read its value as the pivot. - Partition
[lo, hi]in place into three zones: less than, equal to and greater than the pivot. Track the boundariesltandgt. - If
target < lt, sethi = lt - 1. - If
target > gt, setlo = gt + 1. - Otherwise
targetlies in the equal zone, so return the pivot. - Repeat from the pivot step until a value is returned.
Dry run
Run [3, 2, 1, 5, 6, 4] with k = 2, so target = 6 - 2 = 4. Assume the pivots come out as 3 and then 5.
| Round | Range | Pivot | Array after partition | lt, gt | Decision |
|---|---|---|---|---|---|
| 1 | 0..5 | 3 | [2, 1, 3, 4, 6, 5] | 2, 2 | target 4 > gt 2, so lo = 3 |
| 2 | 3..5 | 5 | [2, 1, 3, 4, 5, 6] | 4, 4 | target 4 is in 4..4, return 5 |
In round 1 the left zone holds {2, 1} and the right zone holds {4, 6, 5}. The pivot 3 sits at index 2, which is below the target index 4, so the left side is discarded. In round 2 the pivot lands exactly at index 4. The answer is 5.
Complexity
| Time | O(n) expected, O(n^2) worst case |
|---|---|
| Space | O(1) |
Here n is the array length. Each round scans the current range once, so its cost is proportional to the range size. A random pivot leaves, in expectation, a range a constant fraction smaller. The sizes sum to a geometric series, n + n/2 + n/4 and so on, which is O(n). A run of bad pivots can remove one element per round, giving O(n^2), but that is vanishingly unlikely. The loop is iterative and the partition is in place, so extra space is O(1).
PythonTested in our runner
import random
from typing import List, Optional
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
lo, hi = 0, len(nums) - 1
target = len(nums) - k # index in ascending order
while True:
pivot = nums[random.randint(lo, hi)]
lt, i, gt = lo, lo, hi
# three-way partition: [lo..lt-1] < pivot, [lt..gt] == pivot, [gt+1..hi] > pivot
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 pivot
JavaTested in our runner
import java.util.*;
class Solution {
public int findKthLargest(int[] nums, int k) {
Random rnd = new Random();
int lo = 0, hi = nums.length - 1;
int target = nums.length - k; // index in ascending order
while (true) {
int pivot = nums[lo + rnd.nextInt(hi - lo + 1)];
int lt = lo, i = lo, gt = hi;
// three-way partition: [lo..lt-1] < pivot, [lt..gt] == pivot, [gt+1..hi] > pivot
while (i <= gt) {
if (nums[i] < pivot) {
int t = nums[lt]; nums[lt] = nums[i]; nums[i] = t;
lt++;
i++;
} else if (nums[i] > pivot) {
int t = nums[i]; nums[i] = nums[gt]; nums[gt] = t;
gt--;
} else {
i++;
}
}
if (target < lt) {
hi = lt - 1;
} else if (target > gt) {
lo = gt + 1;
} else {
return pivot;
}
}
}
}
C++Tested in our runner
#include <vector>
#include <cstdlib>
#include <utility>
using namespace std;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int lo = 0, hi = (int)nums.size() - 1;
int target = (int)nums.size() - k; // index in ascending order
while (true) {
int pivot = nums[lo + rand() % (hi - lo + 1)];
int lt = lo, i = lo, gt = hi;
// three-way partition: [lo..lt-1] < pivot, [lt..gt] == pivot, [gt+1..hi] > pivot
while (i <= gt) {
if (nums[i] < pivot) {
swap(nums[lt], nums[i]);
lt++;
i++;
} else if (nums[i] > pivot) {
swap(nums[i], nums[gt]);
gt--;
} else {
i++;
}
}
if (target < lt) {
hi = lt - 1;
} else if (target > gt) {
lo = gt + 1;
} else {
return pivot;
}
}
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findKthLargest = function(nums, k) {
let lo = 0, hi = nums.length - 1;
const target = nums.length - k; // index in ascending order
while (true) {
const pivot = nums[lo + Math.floor(Math.random() * (hi - lo + 1))];
let lt = lo, i = lo, gt = hi;
// three-way partition: [lo..lt-1] < pivot, [lt..gt] == pivot, [gt+1..hi] > pivot
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;
}
}
};
GoTested in our runner
import "math/rand"
func findKthLargest(nums []int, k int) int {
lo, hi := 0, len(nums)-1
target := len(nums) - k // index in ascending order
for {
pivot := nums[lo+rand.Intn(hi-lo+1)]
lt, i, gt := lo, lo, hi
// three-way partition: [lo..lt-1] < pivot, [lt..gt] == pivot, [gt+1..hi] > pivot
for 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
}
}
}
C#Tested in our runner
public class Solution {
public int findKthLargest(int[] nums, int k) {
var rnd = new Random();
int lo = 0, hi = nums.Length - 1;
int target = nums.Length - k; // index in ascending order
while (true) {
int pivot = nums[lo + rnd.Next(hi - lo + 1)];
int lt = lo, i = lo, gt = hi;
// three-way partition: [lo..lt-1] < pivot, [lt..gt] == pivot, [gt+1..hi] > pivot
while (i <= gt) {
if (nums[i] < pivot) {
int t = nums[lt]; nums[lt] = nums[i]; nums[i] = t;
lt++;
i++;
} else if (nums[i] > pivot) {
int t = nums[i]; nums[i] = nums[gt]; nums[gt] = t;
gt--;
} else {
i++;
}
}
if (target < lt) {
hi = lt - 1;
} else if (target > gt) {
lo = gt + 1;
} else {
return pivot;
}
}
}
}
Common mistakes
- Counting distinct values, for example
set(nums)before sorting. The problem counts duplicates, so[3, 3, 3]withk = 2returns 3. Work on the raw array. - Using the wrong index after an ascending sort, such as
nums[k - 1]ornums[n - k - 1]. The kth largest in ascending order sits atn - k. Check it on[1, 2]withk = 1, which must give 2. - Using a max-heap of size k. A max-heap root is the largest value, not the kth. Use a min-heap, so the root is the smallest of the top k and can be evicted when something bigger arrives.
- Popping after the loop or checking
size > kbefore the push. The usual form pushes first and then pops when the size is k + 1. Skipping the check, or popping one time too many, returns the (k+1)th or (k-1)th value. - Sorting in JavaScript with
nums.sort()and no comparator. The default order compares strings, so 10 sorts before 9 and negatives sort wrongly. Pass(a, b) => a - b. - Quickselect with a two-way partition and a fixed pivot such as the last element. Sorted input or many equal values then trigger the O(n^2) path. Use a random pivot and a three-way split so equal values are settled in one pass.
Edge cases
nums = [5],k = 1: a single element returns 5 with every approach.k = n: the answer is the minimum. For[3, 1, 2]withk = 3the result is 1, and the heap keeps all elements.k = 1: the answer is the maximum. The heap never holds more than one value.- All values equal, for example
[7, 7, 7, 7]withk = 2: the answer is 7. Quickselect finishes in one round because every element lands in the equal zone. - Negative values and duplicates, such as
[-1, -1, -2]withk = 2: sorted ascending is[-2, -1, -1], so the answer is -1. - Already sorted or reverse-sorted input of size 10^5: a fixed-pivot quickselect would degrade here, while a random pivot stays linear in expectation.
Follow-ups interviewers ask
- Can you solve it without sorting?
- Yes. A size-k min-heap runs in O(n log k) time and O(k) space. Quickselect runs in O(n) expected time and O(1) extra space, because it only partitions around a pivot and keeps the side holding index n - k.
- How would you handle a stream of numbers where you must report the kth largest after each insert?
- Keep the min-heap of size k as persistent state. For each new value, push it and pop if the size passes k. The root is then the answer in O(log k). You cannot use quickselect here because it needs the whole array up front.
- What if the data does not fit in memory?
- The heap approach still works, because it reads values one at a time and stores only k of them. If k itself is too large, bucket values by range in one pass to find which bucket holds the target rank, then process only that bucket. With the bounded value range in this problem, you can also count occurrences per value and walk the counts from the top.
Kth Largest Element in an Array FAQ
What is the time complexity of Kth Largest Element in an Array?
Sorting costs O(n log n). The min-heap of size k costs O(n log k). Quickselect costs O(n) on average and O(n^2) in the worst case, which a random pivot makes very unlikely.
Why use a min-heap for Kth Largest Element in an Array?
The min-heap root is the smallest of the k largest values seen so far. That is the weakest member of the top k, so it is the one to evict when a larger value arrives. After one pass the root is the kth largest.
Can Kth Largest Element in an Array be solved in O(1) extra space?
Yes, with in-place quickselect, which only swaps elements and keeps a few indices. It does modify the input array. The heap approach needs O(k) space, and a copying sort needs O(n).
Is the kth largest element the same as the kth distinct largest?
No. Duplicates each take a position. In [3, 2, 3, 1, 2, 4, 5, 5, 6] the sorted descending order is 6, 5, 5, 4, 3, 3, 2, 2, 1, so the 4th largest is 4.
Is sorting an acceptable answer for LeetCode 215?
It passes the judge, since n is at most 10^5 and O(n log n) is fast enough. In an interview, state it as the baseline. Then give the heap or quickselect solution to show you can avoid ordering elements you do not need.
Should I use a min-heap or a max-heap for the kth largest element?
A min-heap of size k uses O(k) memory and gives the answer at the root. A max-heap over all n values also works by popping k - 1 times, but it costs O(n) space and O(n + k log n) time.
Asked at
See which companies ask this — Pro
Related problems
- Top K Frequent Elements · same technique: Top K Elements (Selection/Frequency)
- K Closest Points to Origin · same technique: Top K Elements (Selection/Frequency)
- Sort Characters By Frequency · same technique: Top K Elements (Selection/Frequency)
- Last Stone Weight · same technique: Top K Elements (Selection/Frequency)
- Kth Largest Element in a Stream · same technique: Top K Elements (Selection/Frequency)
- Merge k Sorted Lists · next harder, same pattern
- Meeting Rooms II · same pattern: Heap (Priority Queue) Patterns
- Design Twitter · same pattern: Heap (Priority Queue) Patterns
- Reorganize String · same pattern: Heap (Priority Queue) Patterns
- Single-Threaded CPU · same pattern: Heap (Priority Queue) Patterns