Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
K Most Frequent Elements
00:00
5 left

K Most Frequent Elements

EasyPython

Problem

Inc.'s ranking pipeline receives an integer array of event values. Return the k values that occur most frequently.

Count each distinct value, then select the k highest-frequency values. If two values have the same frequency, return the smaller value first. The final result must therefore be ordered by decreasing frequency, followed by increasing numeric value.

Formal Specification

Implement top_k_frequent(nums, k). The input nums is a list of integers, and k is an integer. Return a list containing exactly k distinct integers, ordered according to the rules above.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= number of distinct values in nums
  • -10^9 <= nums[i] <= 10^9
  • The input contains at least k distinct values

Function Signature

def top_k_frequent(nums, k):
Interviewer

Your question is K Most Frequent Elements. Start with the requirements in the Question tab.

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.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.