Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top-K Frequent With PriorityQueue

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

Your question is Top-K Frequent With PriorityQueue. 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

Qualys telemetry pipelines may need to identify the most frequent event codes in a batch for prioritization. Given an integer array of event codes, return the k codes with the highest frequencies using a frequency map and a bounded priority queue.

Formal Specification

Implement top_k_frequent(nums, k), where nums is a list of integers and k is the number of results to return. Return a list containing exactly k distinct integers, ordered by decreasing frequency. If two codes have the same frequency, order the smaller code first.

Your solution should maintain a min-heap of at most k entries while processing the frequency map. The heap should remove the least useful candidate whenever it grows beyond k.

Constraints

  • 1 <= len(nums) <= 10^5
  • 1 <= k <= number of distinct values in nums
  • -10^9 <= nums[i] <= 10^9
  • The result contains exactly k distinct values
  • Ties are ordered by ascending numeric value

Function Signature

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