ToolMight Logo
MediumHeap & Priority QueueArrays & HashingMin-Heap Top-KQuickselect Partitioning

Kth Largest Element in an Array

Locate the kth largest integer in an unsorted array without full sorting. Compare a size-K streaming Min-Heap with average-O(n) Randomized Quickselect.

Optimal Time
O(n log k)
Optimal Space
O(k)
Primary Pattern
Min-Heap Top-K
Visualizer
Open Interactive View →

Problem Statement

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Examples & Constraints

Example 1
Input: nums = [3, 2, 1, 5, 6, 4], k = 2
Output: 5
Explanation: Sorted in descending order: [6, 5, 4, 3, 2, 1]. The 2nd largest element is 5.
Example 2
Input: nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
Output: 4
Explanation: Sorted in descending order: [6, 5, 5, 4, 3, 3, 2, 2, 1]. The 4th largest element is 4.
Constraints
  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

Pattern Recognition & Core Invariant

How to Spot This Pattern

Top-K or Kth-ranked queries over unsorted arrays avoid full O(n log n) sorting by either maintaining a size-K heap or running Quickselect partitioning on only the relevant side.

Core Invariant

A Min-Heap capped at size K holds the K largest elements seen so far with the smallest of them (the Kth largest) at root; Quickselect places pivot at its exact sorted rank in O(n) average time.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Min-Heap of Size K (Streaming Pattern)Optimal
O(n log k)O(k)Maintain a Min-Heap of capacity K. Stream numbers into the heap and pop the smallest whenever size exceeds K. The root will always hold the Kth largest element in O(n log k) time.
2. Randomized Quickselect (3-Way Partition)
O(n) averageO(1) iterative / O(log n) stackPartition around a random pivot into <, ==, and > regions in-place, discarding whichever side cannot contain rank (n - k) for O(n) expected time.

1. Min-Heap of Size K (Streaming Pattern)

Optimal
TimeO(n log k)
SpaceO(k)

Maintain a Min-Heap of capacity K. Stream numbers into the heap and pop the smallest whenever size exceeds K. The root will always hold the Kth largest element in O(n log k) time.

Time ComplexityO(n log k)

Each of the N elements is pushed into a heap of size at most K. Heap push and pop operations take O(log k) time. For k << n, this is much faster than full sorting O(n log n).

Space ComplexityO(k)

The min-heap stores at most K + 1 elements at any point in time.

How It Works

The Invariant: The Bounded VIP Lounge

Instead of sorting the entire array of size N in O(n log n) time, think of a VIP room that only holds K people:

  1. A Min-Heap keeps the smallest of its current members at the top (root) in O(1) peek time.
  2. For each number num in nums:
  • Push num into the Min-Heap.
  • If the heap size exceeds k, pop the top element.
  • What was popped? The smallest value among the top K + 1 elements!
  1. After processing all N elements, the heap contains the K largest elements seen across the entire array.
  2. Who is at the top of this Min-Heap? The smallest among the K largest elements — which is mathematically the Kth largest element!

Why Engineers Love This in Production

This approach is a streaming algorithm. If the input stream contains 10 billion numbers but you only need the Top-10 (k = 10), you do not need to store 10 billion items in memory! You only need a 10-element heap, using O(k) space regardless of stream length.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1nums = [3, 2, 1, 5, 6, 4], k = 2

Initialize empty Min-Heap of capacity 2. Stream elements one by one.

State:heap = []
Strengths
  • +Optimal O(k) memory footprint
  • +Streams data without needing all items in memory simultaneously
Trade-offs
  • -O(n log k) runtime is slower than average-O(n) Quickselect when k is near n/2

Reference Implementation

Complete implementation for Min-Heap of Size K (Streaming Pattern) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
import heapq
def find_kth_largest(nums: list[int], k: int) -> int:
min_heap = []
for num in nums:
heapq.heappush(min_heap, num)
if len(min_heap) > k:
heapq.heappop(min_heap)
return min_heap[0]
if __name__ == "__main__":
test1 = [3, 2, 1, 5, 6, 4]
k1 = 2
test2 = [3, 2, 3, 1, 2, 4, 5, 5, 6]
k2 = 4
print("test1 2nd largest:", find_kth_largest(test1, k1))
print("test2 4th largest:", find_kth_largest(test2, k2))

2. Randomized Quickselect (3-Way Partition)

TimeO(n) average
SpaceO(1) iterative / O(log n) stack

Partition around a random pivot into <, ==, and > regions in-place, discarding whichever side cannot contain rank (n - k) for O(n) expected time.

Time ComplexityO(n) average

Geometrically shrinking search segments sum to n + n/2 + n/4 + ... = 2n work in expectation.

Space ComplexityO(1) iterative / O(log n) stack

Operates in-place without allocating extra arrays or heaps.

How It Works

Average Linear Selection Without Full Sorting

Full QuickSort recurses on both halves (O(n log n)). When searching only for index target = n - k in ascending sorted order, we recurse on only the half containing `target`:

T(n) = T(n / 2) + O(n) = O(n) expected time

Using 3-way partitioning (lt, eq, gt) with a random pivot guarantees linear O(n) speed even when thousands of elements equal the pivot.

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Target Rank for [3, 2, 1, 5, 6, 4], k = 2

2nd largest in ascending sorted array sits at index target = 6 - 2 = 4.

State:targetIdx = 4
Strengths
  • +Expected O(n) linear runtime without sorting
  • +In-place O(1) space with iterative loop; 3-way partition handles duplicate runs
Trade-offs
  • -Mutates the input array in-place
  • -Theoretical worst-case remains O(n²) if random pivots consistently hit extremes

Reference Implementation

Complete implementation for Randomized Quickselect (3-Way Partition) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
import random
def find_kth_largest_quickselect(nums: list[int], k: int) -> int:
def select(arr: list[int], k_largest: int) -> int:
pivot = random.choice(arr)
left = [x for x in arr if x > pivot]
mid = [x for x in arr if x == pivot]
right = [x for x in arr if x < pivot]
if k_largest <= len(left):
return select(left, k_largest)
if k_largest <= len(left) + len(mid):
return pivot
return select(right, k_largest - len(left) - len(mid))
return select(nums, k)
Interactive Visualizer

Trace Heap & Priority Queue mechanics in memory

Step through custom inputs in the Heap & Priority Queue visualizer to inspect pointer updates, array shifts, and call-stack state alongside Kth Largest Element in an Array.

Open Heap & Priority Queue visualizer

Frequently Asked Questions

Why do we use a Min-Heap instead of a Max-Heap?

A Min-Heap capped at size k exposes the smallest among the largest k elements at its root for O(1) eviction, keeping space O(k). A Max-Heap must keep all n elements in O(n) memory.

What is Quickselect and when should I use Min-Heap vs Quickselect?

Quickselect guarantees O(n) average time in-place (O(1) space), whereas a size-K Min-Heap supports read-only data streams and guarantees O(n log k) worst-case runtime.

Why does 3-way partitioning matter in Quickselect?

Arrays packed with thousands of identical values make standard 2-way Lomuto partitioning degrade toward O(n²) even with random pivots. Grouping < pivot, == pivot, and > pivot collapses equal duplicates cleanly in one pass.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Duplicate elements (e.g., [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 -> 4) count separately, NOT deduplicated.
  • Massive duplicate-filled input (e.g., 50,000 copies of 1) degrades naive Lomuto Quickselect to O(n²) unless randomized + 3-way partitioning (or Min-Heap) is used.
  • Boundary values k = 1 (global maximum) and k = nums.length (global minimum).

Common Bugs to Avoid

  • Deduplicating array values first instead of counting duplicates in sorted rank order.
  • Building a Max-Heap over all N elements (which consumes O(n) space instead of O(k)) rather than a Min-Heap of capacity K.
  • Implementing deterministic Quickselect without randomization or duplicate handling, hitting O(n²) timeouts on sorted or all-equal adversarial arrays.

Interview Follow-Up Variations

  • Kth Largest Element in a Stream: keep a persistent size-K Min-Heap handling incoming add(val) updates in O(log k).
  • Counting / Bucket Sort approach (O(n + range)): because `-10^4 <= nums[i] <= 10^4`, counting frequencies resolves queries deterministically in linear time.

Related Problems

All problems
EasyArrays & Hashing

Contains Duplicate

Check whether any integer repeats inside an array. Compare early-exit O(n) Hash Set membership testing against O(1)-space in-place sorting.

Pattern: Hash Set
O(n) · O(n)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
EasyArrays & Hashing

Valid Anagram

Check whether string t is an anagram of string s. Compare O(n log n) canonical sorting against an O(n) fixed 26-letter frequency bucket balance.

Pattern: Frequency Counting
O(n) · O(1)
Solve