Your question is Top K Frequent Items Data Structure. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
Goldman Sachs Asset & Wealth Management processes item events for analytics surfaces such as internal portfolio research workflows. Implement a data structure that tracks item frequencies while supporting efficient updates and top-K queries.
Write top_k_frequent(operations, k), which processes operations in order and returns the result of every query.
operations is a list of operations. Each operation is either ["add", item], ["remove", item], or ["query"].item is a non-empty string.k is a positive integer.add increases an item's frequency by one.remove decreases an item's frequency by one, but never below zero. Removing an absent item has no effect.query returns up to k currently tracked items, ordered by descending frequency. Items with equal frequencies are ordered lexicographically.query, in query order.Design the solution for many updates and queries. A query should not require sorting every tracked item from scratch.
def top_k_frequent(operations, k):