VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 09: Heaps and top-k

Lesson 9.3 of 12 in this module Unrolled Pro

Kth Largest Element in an Array

The k-th largest value of an unsorted array without sorting it. From sorting (O(n log n)), to a min-heap that keeps only the k largest seen so far (O(n log k), O(k) memory, works on streams), to quickselect, which partitions around a random pivot and recurses into one side only (O(n) on average), with three-way partitioning for duplicates. Then a stream of scores, k close to n, small integer ranges with counting, and data split across machines.

about 10 min 5 Python examples 2 quick checks

Problem. Given an integer array nums and k, return the k-th largest element (in sorted order, not the k-th distinct).

text
nums = [3, 2, 1, 5, 6, 4],          k = 2   →   5
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4   →   4

Sorting answers it, but sorts n − 1 elements you don't care about. The two classic improvements trade in different directions: a heap of size k uses little memory and works on streams; quickselect is linear on average but needs the whole array in memory.

ML context. "The k-th largest score" is a threshold: keep the top 1% of candidates by relevance, the 95th percentile of latencies, the cutoff for top-k sampling over logits, the score above which a classifier flags the k highest-risk cases. PyTorch's torch.topk and NumPy's np.partition implement exactly the two ideas here.


1. Step 1: Clarify

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Kth Largest Element in an Array"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee