Design a streaming top-K frequent items tracker with lexicographic tie-breaking

Quick Overview

Design a data structure that counts items from a stream and returns the K most frequent ones, ordered by count with ties broken alphabetically. It tests hash map counting, ordered structures, incremental updates, and choosing a design that fits the mix of reads and writes.

Design a streaming top-K frequent items tracker with lexicographic tie-breaking

Company: Perplexity

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a data structure that ingests a continuous stream of items and maintains a real-time view of the `K` most frequent elements observed so far. The structure is initialized with an integer `K`. As items arrive through `add`, their frequency counts are updated. A call to `getTopK` returns the `K` items with the highest frequencies, sorted by frequency descending, with ties broken by lexicographic ascending order of the item string. If fewer than `K` distinct items have been observed, return all observed items, still sorted by the same rules. Implement the following methods: - `TopKFrequentStream(k: int)`: create the structure for a given `K`. - `add(item: str)`: record one occurrence of `item` from the stream. - `getTopK() -> List[str]`: return the `K` most frequent items seen so far, sorted by frequency descending, breaking ties lexicographically ascending. If fewer than `K` distinct items have been observed, return all of them. Example 1: ```text Input: ["TopKFrequentStream", "add", "add", "add", "add", "add", "getTopK", "add", "add", "getTopK"] [[2], ["pear"], ["fig"], ["fig"], ["kiwi"], ["kiwi"], [], ["pear"], ["pear"], []] Output: [null, null, null, null, null, null, ["fig", "kiwi"], null, null, ["pear", "fig"]] ``` After the first five adds the counts are pear 1, fig 2 and kiwi 2. Fig and kiwi tie at 2, and "fig" sorts first. Two more occurrences of pear raise it to 3, so it leads, and fig still beats kiwi on the tie for the second slot. Example 2: ```text Input: ["TopKFrequentStream", "getTopK", "add", "getTopK", "add", "add", "getTopK"] [[3], [], ["dog"], [], ["cat"], ["dog"], []] Output: [null, [], null, ["dog"], null, null, ["dog", "cat"]] ``` With `K = 3`, the first call returns an empty list because nothing has arrived yet. After one "dog" there is only one distinct item. After "cat" and a second "dog" the counts are dog 2 and cat 1, and both are returned because fewer than 3 distinct items have been seen. ```hint Start simple Exact counts in a hash map make `add` cheap. Work out what `getTopK` costs if it does all of the ordering work, and decide when that cost is acceptable. ``` ```hint Counts only go up Each `add` raises one item's count by exactly one. Ask which items can enter or leave the current top K after a single `add`. ``` ### Constraints & Assumptions - `1 <= K <= 10^4` - `1 <= item.length <= 20` - `item` consists of lowercase English letters. - At most `10^5` total calls to `add` and `getTopK`. ### Clarifying Questions to Ask - How often is `getTopK` called compared with `add`? That decides whether the ordering work belongs in `add` or in `getTopK`. - Must the counts be exact, or is an approximate top K acceptable if the number of distinct items grows too large for memory? - Is the structure used from a single thread, or do many writers call `add` concurrently? ### What a Strong Answer Covers - The exact ordering rule (frequency descending, then item ascending) and the case of fewer than `K` distinct items. - Exact counting with a hash map, with the cost of `add` and `getTopK` stated for the chosen design. - When sorting on every query stops being acceptable, and a design that moves the work into `add` for query-heavy workloads. - Correctness of any incremental structure under ties, including which item leaves when a new one enters the top K. - How memory grows with the number of distinct items, and what approximate counting gives up. ### Follow-up Questions - How would the design change if `getTopK` took `k` as a parameter on each call instead of fixing it at construction? - How would you report the top K over a sliding window, such as the last hour, where counts can also go down? - If the distinct items no longer fit in memory, how would you approximate the top K, and what guarantee would you lose? - How would you make the structure safe and fast with many concurrent writers?

Overview: Design a data structure that counts items from a stream and returns the K most frequent ones, ordered by count with ties broken alphabetically. It tests hash map counting, ordered structures, incremental updates, and choosing a design that fits the mix of reads and writes.

Perplexity logo
Perplexity
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a data structure that ingests a continuous stream of items and maintains a real-time view of the K most frequent elements observed so far.

The structure is initialized with an integer K. As items arrive through add, their frequency counts are updated. A call to getTopK returns the K items with the highest frequencies, sorted by frequency descending, with ties broken by lexicographic ascending order of the item string.

If fewer than K distinct items have been observed, return all observed items, still sorted by the same rules.

Implement the following methods:

  • TopKFrequentStream(k: int) : create the structure for a given K .
  • add(item: str) : record one occurrence of item from the stream.
  • getTopK() -> List[str] : return the K most frequent items seen so far, sorted by frequency descending, breaking ties lexicographically ascending. If fewer than K distinct items have been observed, return all of them.

Example 1:

Input:
["TopKFrequentStream", "add", "add", "add", "add", "add", "getTopK", "add", "add", "getTopK"]
[[2], ["pear"], ["fig"], ["fig"], ["kiwi"], ["kiwi"], [], ["pear"], ["pear"], []]

Output: [null, null, null, null, null, null, ["fig", "kiwi"], null, null, ["pear", "fig"]]

After the first five adds the counts are pear 1, fig 2 and kiwi 2. Fig and kiwi tie at 2, and "fig" sorts first. Two more occurrences of pear raise it to 3, so it leads, and fig still beats kiwi on the tie for the second slot.

Example 2:

Input:
["TopKFrequentStream", "getTopK", "add", "getTopK", "add", "add", "getTopK"]
[[3], [], ["dog"], [], ["cat"], ["dog"], []]

Output: [null, [], null, ["dog"], null, null, ["dog", "cat"]]

With K = 3, the first call returns an empty list because nothing has arrived yet. After one "dog" there is only one distinct item. After "cat" and a second "dog" the counts are dog 2 and cat 1, and both are returned because fewer than 3 distinct items have been seen.

Constraints & Assumptions

  • 1 <= K <= 10^4
  • 1 <= item.length <= 20
  • item consists of lowercase English letters.
  • At most 10^5 total calls to add and getTopK .

Clarifying Questions to Ask Guidance

  • How often is getTopK called compared with add ? That decides whether the ordering work belongs in add or in getTopK .
  • Must the counts be exact, or is an approximate top K acceptable if the number of distinct items grows too large for memory?
  • Is the structure used from a single thread, or do many writers call add concurrently?

What a Strong Answer Covers Guidance

  • The exact ordering rule (frequency descending, then item ascending) and the case of fewer than K distinct items.
  • Exact counting with a hash map, with the cost of add and getTopK stated for the chosen design.
  • When sorting on every query stops being acceptable, and a design that moves the work into add for query-heavy workloads.
  • Correctness of any incremental structure under ties, including which item leaves when a new one enters the top K.
  • How memory grows with the number of distinct items, and what approximate counting gives up.

Follow-up Questions Guidance

  • How would the design change if getTopK took k as a parameter on each call instead of fixing it at construction?
  • How would you report the top K over a sliding window, such as the last hour, where counts can also go down?
  • If the distinct items no longer fit in memory, how would you approximate the top K, and what guarantee would you lose?
  • How would you make the structure safe and fast with many concurrent writers?