Problem. Given an integer array nums and k, return the k most frequent elements, in any order. The answer is
guaranteed to be unique.
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).