Kth Largest Element in an Array
A medium Arrays problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 2
- Core for
- 25 roles
- Platform
- LeetCode
The problem
Find the kth largest element in an unsorted integer array without sorting the entire array.
Example 1
- Input
- nums = [3,2,1,5,6,4], k = 2
- Output
- 5
- Why
- The sorted array descending is [6,5,4,3,2,1], so the 2nd largest value is 5.
Example 2
- Input
- nums = [3,2,3,1,2,4,5,5,6], k = 4
- Output
- 4
- Why
- In descending sorted order [6,5,5,4,3,3,2,2,1], the 4th largest entry is 4.
Example 3
- Input
- nums = [1], k = 1
- Output
- 1
- Why
- The lone element is trivially the 1st largest value.
Constraints
- 1 <= k <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
How to think about it
Updated 2026-09-09Locating the kth largest element does not require establishing total order across all n items. An order-statistic pivot splits elements into those larger and smaller than itself, placing the pivot in its permanent rank. If that rank matches k, you finish immediately; otherwise, exactly one partition is discarded and the other recursed into.
Approaches, worst first
Complete array sort
time O(n log n) · space O(1)
Sort the array ascending and index nums[n - k], or sort descending and take nums[k - 1]. Extremely concise to implement, but orders every single element and pays unnecessary O(n log n) overhead.
Bounded min-heap tracking
time O(n log k) · space O(k)
Push elements one by one into a min-heap, popping the root whenever the heap size exceeds k. At the conclusion of the array traversal, the heap holds the k largest values and the top element is the kth largest.
Quickselect partition discardingWrite this one
time O(n) · space O(1)
Choose a pivot, partition the array so that elements smaller than the pivot sit to the left and larger to the right, and check the pivot index. Recurse only into the side containing the target rank, halving the search space on average at each step.
Where people lose marks · 3
- Confusing kth largest with kth distinct element, failing when duplicate values exist in the input.
- Deterministic pivot selection on already sorted or adversarially constructed arrays causing worst-case quadratic runtime in quickselect.
- Using a max-heap of size n instead of a min-heap of size k, consuming O(n) space and O(n + k log n) time.
Full solution
Quickselect with a random pivot: one Lomuto partition fixes the pivot at its final rank, and only the side holding index n - k is kept, giving O(n) average time in place. It beats the O(n log k) heap in an interview because it uses no extra space and never orders what it discards.
Python
import random
def find_kth_largest(nums: list[int], k: int) -> int:
target = len(nums) - k # index the answer would occupy in ascending order
lo, hi = 0, len(nums) - 1
while True:
# Random pivot keeps sorted or adversarial inputs off the quadratic path.
pivot_idx = random.randint(lo, hi)
nums[lo], nums[pivot_idx] = nums[pivot_idx], nums[lo]
pivot = nums[lo]
store = lo + 1 # everything before store is < pivot
for j in range(lo + 1, hi + 1):
if nums[j] < pivot:
nums[store], nums[j] = nums[j], nums[store]
store += 1
p = store - 1
nums[lo], nums[p] = nums[p], nums[lo] # pivot lands at its final rank p
if p == target:
return nums[p]
if p < target:
lo = p + 1 # answer is in the larger-than-pivot side
else:
hi = p - 1
JavaScript
function findKthLargest(nums, k) {
const target = nums.length - k; // index the answer would occupy in ascending order
let lo = 0;
let hi = nums.length - 1;
while (true) {
// Random pivot keeps sorted or adversarial inputs off the quadratic path.
const pivotIdx = lo + Math.floor(Math.random() * (hi - lo + 1));
[nums[lo], nums[pivotIdx]] = [nums[pivotIdx], nums[lo]];
const pivot = nums[lo];
let store = lo + 1; // everything before store is < pivot
for (let j = lo + 1; j <= hi; j++) {
if (nums[j] < pivot) {
[nums[store], nums[j]] = [nums[j], nums[store]];
store++;
}
}
const p = store - 1;
[nums[lo], nums[p]] = [nums[p], nums[lo]]; // pivot lands at its final rank p
if (p === target) return nums[p];
if (p < target) lo = p + 1; // answer is in the larger-than-pivot side
else hi = p - 1;
}
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .