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

Lesson 9.5 of 12 in this module Unrolled Pro

Top K Frequent Elements

The k most frequent values in an array. From counting with a hash map and sorting all distinct values by count (O(n + u log u)), to a min-heap of size k over the counts (O(n + u log k)), to bucket sort by frequency, which is O(n) because a count can never exceed n. Then ties broken alphabetically, a stream too large to count exactly (the Misra–Gries heavy-hitters summary with its guarantee), counts spread across machines, and building a vocabulary from token frequencies.

about 10 min 4 Python examples 2 quick checks

Problem. Given an integer array nums and k, return the k most frequent elements, in any order. The answer is guaranteed to be unique.

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

Two steps hide in it: count (a hash map, module 02) and select the top k counts (this module). Counting is always O(n); the choices are all in the selection, where u, the number of distinct values, matters more than n.

ML context. Building a tokenizer vocabulary keeps the most frequent tokens or merges; data analysis looks for the most common labels, queries or error messages; monitoring wants the "heavy hitters" among millions of user ids or endpoints. At that scale you often can't even store all the counts, which is where approximate summaries come in (Change B).


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 "Top K Frequent Elements"

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