Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top K Frequent Items Data Structure

HardPython00:00
Practice interviewer
In session
5 left
00:00

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.

You need to log in / sign up to run or submit.

Problem

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.

Formal Specification

  • 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.
  • The function returns a list containing the output of each query, in query order.

Design the solution for many updates and queries. A query should not require sorting every tracked item from scratch.

Constraints

  • 1 <= len(operations) <= 2 * 10^5
  • 1 <= k <= 10^4
  • There are at most 10^5 distinct item names
  • Each item name is a non-empty ASCII string of length at most 50
  • An operation is exactly ["add", item], ["remove", item], or ["query"]

Function Signature

def top_k_frequent(operations, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output