Design a data structure for dynamic top‑K frequency
BloombergSoftware Engineer · Technical ScreenLast updated
This question evaluates data structure and algorithm design skills, focusing on frequency counting, dynamic maintenance of top-K elements, and efficient update and query operations in a multiset within the Coding & Algorithms domain.
Design a data structure that maintains a multiset of integers and supports the following operations efficiently:
Operations
insert(x): Add one occurrence of valuex.remove(x): Remove one occurrence of valuexif it exists (ifxis not present, do nothing).topK(k) -> List[int]: Return the k most frequent values currently in the multiset.
Requirements / Clarifications
- Frequency means the current count of each value in the multiset.
- If fewer than
kdistinct values exist, return all distinct values. - If multiple values have the same frequency, you may return them in any order (or state and implement a deterministic tie-break such as smaller value first).
- Discuss time and space complexity for each operation.
- Explain why your chosen data structures are appropriate compared with alternatives (e.g., sorting on every query, balanced BST/TreeMap, etc.).
- Consider edge cases (removing down to zero, repeated inserts/removes, large
k, empty structure). - Bonus discussion: how would your approach change if the number of total updates is extremely large (e.g., up to billions)?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.