Kth Largest Element in an Array

MediumQuickSelect · Heap🧩 Partitioning & QuickselectLeetCode #215 ↗Updated

Problem

Given an integer array nums and an integer k, return the value that would sit at position k if the array were sorted in descending order (duplicates count separately). Can you avoid fully sorting?
Input[3,2,1,5,6,4], k=2Output5
Input[3,2,3,1,2,4,5,5,6], k=4Output4

1 ≤ k ≤ n ≤ 105  ·  -104 ≤ nums[i] ≤ 104

Try it yourself

Java
class Solution {
    public int findKthLargest(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The k-th largest is the element at index n-k of the sorted array. A partition step puts one pivot in its final sorted slot — so only recurse into the one side that contains index n-k (n + n/2 + n/4 … = O(n) on average).
PatternPartitioning & Quickselect

Instinct Need the k-th smallest/largest, an unordered top-k, or values grouped into buckets in place - partition around a pivot and chase only one side.

Memory hack Pivot, partition, pick a side - quickselect is quicksort's lazy cousin that only chases the half holding k.

Open the Partitioning & Quickselect guide →

Approaches

Brute ForceSort, then Index

Time O(n log n)Space O(log n)

Sort ascending; the k-th largest is then simply nums[n - k]. Sorting orders everything, which is far more work than finding one rank.

Java
public int findKthLargest(int[] nums, int k) {
    Arrays.sort(nums);
    return nums[nums.length - k];
}

One line and safe, but does a full sort for a single answer.

At a glance

LevelApproachTimeSpace
Brute ForceSort, then IndexO(n log n)O(log n)
BetterMin-Heap of Size kO(n log k)O(k)
OptimalQuickSelect (Random Pivot, 3-Way Partition)O(n) avg, O(n²) worstO(1)
Common pitfalls
  • Mixing up k-th largest (index n-k) with k-th smallest (k-1).
  • Fixed first/last pivot — sorted input makes QuickSelect O(n²).
  • 2-way partition with many duplicates — degrades to O(n²) (LeetCode has such tests).
Interview tips
  • Give the heap solution first; it also works on streams.
  • Explain the average O(n): each round keeps about half, n + n/2 + … ≤ 2n.
  • Mention that QuickSelect mutates the input — copy it if the caller needs the order.
Pattern
Top-k / k-th order statistic → min-heap of size k, or QuickSelect when one rank is needed.
My notes saved in this browser