Interview conceptData Manipulation (SQL/Python)

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(*) with GROUP BY for frequencies; rank by frequency DESC, then the stated tie-break column.
  • Use ROW_NUMBER(), RANK(), or DENSE_RANK() over partitions; choose DENSE_RANK when equal values share a salary level.
  • Extract URL components with SPLIT_PART, SUBSTRING, or REGEXP_REPLACE; filter dates before aggregation to reduce rows.
  • For Python frequency counts, use collections.Counter or a dictionary; sorting costs O(n log n) time and O(u) space.
  • For fixed small k, maintain a size-k min-heap keyed by frequency and tie priority; updates cost O(log k).
  • Dynamic multiset queries need a frequency map plus ordered structure; support increment, decrement, deletion, and deterministic tie handling.
  • Distinguish ROW_NUMBER from RANK: the former returns exactly k rows, 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, not ROW_NUMBER.

Pitfall: Applying a global LIMIT before 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

Related concepts