Kth Largest Element in an Array
Problem (restated)
Find the kth largest element in an unsorted array (not distinct required).
Intuition
Min-heap of size k holds the largest k seen; root is kth largest. Quick select partitions until index n-k is the pivot.
Approaches
Min-heap of size k
UnverifiedIdea. Push all; pop when size>k; return peek.
Walkthrough. [3,2,1,5,6,4], k=2 → 5.
Trade-offs. Heap O(n log k) vs quickselect average O(n). Prefer the heap when k is tiny or the array must stay intact.
Show helper code
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
private a: T[] = [];
private less: (x: T, y: T) => boolean;
constructor(less: (x: T, y: T) => boolean) {
this.less = less;
}
get size(): number {
return this.a.length;
}
peek(): T {
return this.a[0]!;
}
push(x: T): void {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.less(a[i]!, a[p]!)) break;
[a[i], a[p]] = [a[p]!, a[i]!];
i = p;
}
}
pop(): T {
const a = this.a;
const top = a[0]!;
const last = a.pop()!;
if (a.length) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1;
const r = l + 1;
let s = i;
if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
if (s === i) break;
[a[i], a[s]] = [a[s]!, a[i]!];
i = s;
}
}
return top;
}
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
private a: T[] = [];
private less: (x: T, y: T) => boolean;
constructor(less: (x: T, y: T) => boolean) {
this.less = less;
}
get size(): number {
return this.a.length;
}
peek(): T {
return this.a[0]!;
}
push(x: T): void {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.less(a[i]!, a[p]!)) break;
[a[i], a[p]] = [a[p]!, a[i]!];
i = p;
}
}
pop(): T {
const a = this.a;
const top = a[0]!;
const last = a.pop()!;
if (a.length) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1;
const r = l + 1;
let s = i;
if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
if (s === i) break;
[a[i], a[s]] = [a[s]!, a[i]!];
i = s;
}
}
return top;
}
}
export function findKthLargest(nums: number[], k: number): number {
// Real binary min-heap of size k; its top is the kth largest.
const heap = new Heap<number>((a, b) => a < b);
for (const x of nums) {
if (heap.size < k) {
heap.push(x);
} else if (x > heap.peek()) {
heap.pop();
heap.push(x);
}
}
return heap.peek();
}
export function findKthLargest(nums: number[], k: number): number {
// Real binary min-heap of size k; its top is the kth largest.
const heap = new Heap<number>((a, b) => a < b);
for (const x of nums) {
if (heap.size < k) {
heap.push(x);
} else if (x > heap.peek()) {
heap.pop();
heap.push(x);
}
}
return heap.peek();
}
Quick select
UnverifiedIdea. The kth largest is the element at index n-k in sorted order. Randomized partition until the pivot lands there; loop into only one side. Mutates the array in place.
Walkthrough. [3,2,1,5,6,4], k=2 → target index 4. After partitions the value at index 4 is 5.
Trade-offs. Average O(n), worst O(n²) without a random pivot. The Quick Select default. k is 1-indexed.
export function findKthLargest(nums: number[], k: number): number {
const target = nums.length - k;
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
const p = partition(nums, lo, hi);
if (p === target) return nums[p]!;
if (p < target) lo = p + 1;
else hi = p - 1;
}
return nums[lo]!;
}
function partition(nums: number[], lo: number, hi: number): number {
const rand = lo + Math.floor(Math.random() * (hi - lo + 1));
[nums[rand], nums[hi]] = [nums[hi]!, nums[rand]!];
const pivot = nums[hi]!;
let i = lo;
for (let j = lo; j < hi; j++) {
if (nums[j]! < pivot) {
[nums[i], nums[j]] = [nums[j]!, nums[i]!];
i++;
}
}
[nums[i], nums[hi]] = [nums[hi]!, nums[i]!];
return i;
}
export function findKthLargest(nums: number[], k: number): number {
const target = nums.length - k;
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
const p = partition(nums, lo, hi);
if (p === target) return nums[p]!;
if (p < target) lo = p + 1;
else hi = p - 1;
}
return nums[lo]!;
}
function partition(nums: number[], lo: number, hi: number): number {
const rand = lo + Math.floor(Math.random() * (hi - lo + 1));
[nums[rand], nums[hi]] = [nums[hi]!, nums[rand]!];
const pivot = nums[hi]!;
let i = lo;
for (let j = lo; j < hi; j++) {
if (nums[j]! < pivot) {
[nums[i], nums[j]] = [nums[j]!, nums[i]!];
i++;
}
}
[nums[i], nums[hi]] = [nums[hi]!, nums[i]!];
return i;
}
Template connection
Heap top-K, or Quick Select to rank n-k. Classic kth-largest problem for both patterns.
Reflection
- The top of a min-heap of size
kis the kth largest. Push every value and pop once the size passesk. Quickselect is linear on average. k == nis the smallest value.k == 1is the largest. Duplicates are distinct elements. Do not unique them.- A bad pivot makes quickselect quadratic. The heap stays
O(n log k).