Top-K Frequency Ranking
Asked of: Software Engineer
Last updated
What's being tested
These problems test frequency aggregation followed by ranking, tie-breaking, and returning only the top results. You must translate requirements precisely into GROUP BY/window-function SQL or hash-map plus sorting/heap algorithms, while accounting for ties, duplicates, filters, and ordering complexity.
Patterns & templates
- Use
COUNT(*)withGROUP BYfor frequencies; rank byfrequency DESC, then the stated tie-break column. - Use
ROW_NUMBER(),RANK(), orDENSE_RANK()over partitions; chooseDENSE_RANKwhen equal values share a salary level. - Extract URL components with
SPLIT_PART,SUBSTRING, orREGEXP_REPLACE; filter dates before aggregation to reduce rows. - For Python frequency counts, use
collections.Counteror a dictionary; sorting costsO(n log n)time andO(u)space. - For fixed small
k, maintain a size-kmin-heap keyed by frequency and tie priority; updates costO(log k). - Dynamic multiset queries need a frequency map plus ordered structure; support increment, decrement, deletion, and deterministic tie handling.
- Distinguish
ROW_NUMBERfromRANK: the former returns exactlykrows, while the latter preserves ties and may return more.
Common pitfalls
Pitfall: Sorting only by frequency produces nondeterministic or incorrect results when equal-frequency values require descending numeric order.
Pitfall: Confusing top three employees with top three rows; distinct salary levels require
DENSE_RANK, notROW_NUMBER.
Pitfall: Applying a global
LIMITbefore partitioning or forgetting weekday/date grouping changes the requested result.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Practice questions
- Rank the K Most Common Words With Alphabetical Ties, Then Over a StreamBloomberg · Software Engineer · Technical Screen · medium
- Order Integers by Rarity and Descending TiesBloomberg · Software Engineer · Other · easy
- Find Employees in Their Department’s Top Three Salary LevelsBloomberg · Software Engineer · Other · hard
- Design a data structure for dynamic top‑K frequencyBloomberg · Software Engineer · Technical Screen · hard
- Design auth, session security, and top-N usersBloomberg · Software Engineer · Onsite · hard
- Create SQL report of top extensions by weekdayBloomberg · Software Engineer · Technical Screen · medium
Related concepts
- Top-K Frequency TrackingCoding & Algorithms
- Top-K Queries And Streaming AggregationCoding & Algorithms
- Top-K Selection, Heaps, And RankingCoding & Algorithms
- Top-K Ranking And SelectionSystem Design
- Top-K, Heaps, Quickselect, And Frequency AnalysisCoding & Algorithms
- Heaps, Priority Queues, and Top-K SelectionCoding & Algorithms